4 * Copyright (c) 2003-2008 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25 #include "hw/boards.h"
27 #include "hw/pcmcia.h"
29 #include "hw/audiodev.h"
37 #include "qemu-timer.h"
38 #include "qemu-char.h"
39 #include "cache-utils.h"
41 #include "audio/audio.h"
42 #include "migration.h"
55 #include <sys/times.h>
59 #include <sys/ioctl.h>
60 #include <sys/resource.h>
61 #include <sys/socket.h>
62 #include <netinet/in.h>
64 #if defined(__NetBSD__)
65 #include <net/if_tap.h>
68 #include <linux/if_tun.h>
70 #include <arpa/inet.h>
73 #include <sys/select.h>
81 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
82 #include <freebsd/stdlib.h>
87 #include <linux/rtc.h>
89 /* For the benefit of older linux systems which don't supply it,
90 we use a local copy of hpet.h. */
91 /* #include <linux/hpet.h> */
94 #include <linux/ppdev.h>
95 #include <linux/parport.h>
99 #include <sys/ethernet.h>
100 #include <sys/sockio.h>
101 #include <netinet/arp.h>
102 #include <netinet/in.h>
103 #include <netinet/in_systm.h>
104 #include <netinet/ip.h>
105 #include <netinet/ip_icmp.h> // must come after ip.h
106 #include <netinet/udp.h>
107 #include <netinet/tcp.h>
115 #include "qemu_socket.h"
117 #if defined(CONFIG_SLIRP)
118 #include "libslirp.h"
121 #if defined(__OpenBSD__)
125 #if defined(CONFIG_VDE)
126 #include <libvdeplug.h>
131 #include <sys/timeb.h>
132 #include <mmsystem.h>
133 #define getopt_long_only getopt_long
134 #define memalign(align, size) malloc(size)
141 #endif /* CONFIG_SDL */
145 #define main qemu_main
146 #endif /* CONFIG_COCOA */
150 #include "exec-all.h"
152 //#define DEBUG_UNUSED_IOPORT
153 //#define DEBUG_IOPORT
155 //#define DEBUG_SLIRP
159 # define LOG_IOPORT(...) qemu_log_mask(CPU_LOG_IOPORT, ## __VA_ARGS__)
161 # define LOG_IOPORT(...) do { } while (0)
164 #define DEFAULT_RAM_SIZE 128
166 /* Max number of USB devices that can be specified on the commandline. */
167 #define MAX_USB_CMDLINE 8
169 /* Max number of bluetooth switches on the commandline. */
170 #define MAX_BT_CMDLINE 10
172 /* XXX: use a two level table to limit memory usage */
173 #define MAX_IOPORTS 65536
175 const char *bios_dir = CONFIG_QEMU_SHAREDIR;
176 const char *bios_name = NULL;
177 static void *ioport_opaque[MAX_IOPORTS];
178 static IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
179 static IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
180 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
181 to store the VM snapshots */
182 DriveInfo drives_table[MAX_DRIVES+1];
184 static int vga_ram_size;
185 enum vga_retrace_method vga_retrace_method = VGA_RETRACE_DUMB;
186 static DisplayState *display_state;
190 const char* keyboard_layout = NULL;
191 int64_t ticks_per_sec;
194 NICInfo nd_table[MAX_NICS];
196 static int rtc_utc = 1;
197 static int rtc_date_offset = -1; /* -1 means no change */
198 int cirrus_vga_enabled = 1;
199 int std_vga_enabled = 0;
200 int vmsvga_enabled = 0;
202 int graphic_width = 1024;
203 int graphic_height = 768;
204 int graphic_depth = 8;
206 int graphic_width = 800;
207 int graphic_height = 600;
208 int graphic_depth = 15;
210 static int full_screen = 0;
212 static int no_frame = 0;
215 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
216 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
217 CharDriverState *virtcon_hds[MAX_VIRTIO_CONSOLES];
219 int win2k_install_hack = 0;
224 const char *vnc_display;
225 int acpi_enabled = 1;
231 int graphic_rotate = 0;
233 const char *option_rom[MAX_OPTION_ROMS];
235 int semihosting_enabled = 0;
239 const char *qemu_name;
241 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
242 unsigned int nb_prom_envs = 0;
243 const char *prom_envs[MAX_PROM_ENVS];
246 struct drive_opt drives_opt[MAX_DRIVES];
248 static CPUState *cur_cpu;
249 static CPUState *next_cpu;
250 static int event_pending = 1;
251 /* Conversion factor from emulated instructions to virtual clock ticks. */
252 static int icount_time_shift;
253 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
254 #define MAX_ICOUNT_SHIFT 10
255 /* Compensate for varying guest execution speed. */
256 static int64_t qemu_icount_bias;
257 static QEMUTimer *icount_rt_timer;
258 static QEMUTimer *icount_vm_timer;
259 static QEMUTimer *nographic_timer;
261 uint8_t qemu_uuid[16];
263 /***********************************************************/
264 /* x86 ISA bus support */
266 target_phys_addr_t isa_mem_base = 0;
269 static IOPortReadFunc default_ioport_readb, default_ioport_readw, default_ioport_readl;
270 static IOPortWriteFunc default_ioport_writeb, default_ioport_writew, default_ioport_writel;
272 static uint32_t ioport_read(int index, uint32_t address)
274 static IOPortReadFunc *default_func[3] = {
275 default_ioport_readb,
276 default_ioport_readw,
279 IOPortReadFunc *func = ioport_read_table[index][address];
281 func = default_func[index];
282 return func(ioport_opaque[address], address);
285 static void ioport_write(int index, uint32_t address, uint32_t data)
287 static IOPortWriteFunc *default_func[3] = {
288 default_ioport_writeb,
289 default_ioport_writew,
290 default_ioport_writel
292 IOPortWriteFunc *func = ioport_write_table[index][address];
294 func = default_func[index];
295 func(ioport_opaque[address], address, data);
298 static uint32_t default_ioport_readb(void *opaque, uint32_t address)
300 #ifdef DEBUG_UNUSED_IOPORT
301 fprintf(stderr, "unused inb: port=0x%04x\n", address);
306 static void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
308 #ifdef DEBUG_UNUSED_IOPORT
309 fprintf(stderr, "unused outb: port=0x%04x data=0x%02x\n", address, data);
313 /* default is to make two byte accesses */
314 static uint32_t default_ioport_readw(void *opaque, uint32_t address)
317 data = ioport_read(0, address);
318 address = (address + 1) & (MAX_IOPORTS - 1);
319 data |= ioport_read(0, address) << 8;
323 static void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
325 ioport_write(0, address, data & 0xff);
326 address = (address + 1) & (MAX_IOPORTS - 1);
327 ioport_write(0, address, (data >> 8) & 0xff);
330 static uint32_t default_ioport_readl(void *opaque, uint32_t address)
332 #ifdef DEBUG_UNUSED_IOPORT
333 fprintf(stderr, "unused inl: port=0x%04x\n", address);
338 static void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
340 #ifdef DEBUG_UNUSED_IOPORT
341 fprintf(stderr, "unused outl: port=0x%04x data=0x%02x\n", address, data);
345 /* size is the word size in byte */
346 int register_ioport_read(int start, int length, int size,
347 IOPortReadFunc *func, void *opaque)
353 } else if (size == 2) {
355 } else if (size == 4) {
358 hw_error("register_ioport_read: invalid size");
361 for(i = start; i < start + length; i += size) {
362 ioport_read_table[bsize][i] = func;
363 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
364 hw_error("register_ioport_read: invalid opaque");
365 ioport_opaque[i] = opaque;
370 /* size is the word size in byte */
371 int register_ioport_write(int start, int length, int size,
372 IOPortWriteFunc *func, void *opaque)
378 } else if (size == 2) {
380 } else if (size == 4) {
383 hw_error("register_ioport_write: invalid size");
386 for(i = start; i < start + length; i += size) {
387 ioport_write_table[bsize][i] = func;
388 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
389 hw_error("register_ioport_write: invalid opaque");
390 ioport_opaque[i] = opaque;
395 void isa_unassign_ioport(int start, int length)
399 for(i = start; i < start + length; i++) {
400 ioport_read_table[0][i] = default_ioport_readb;
401 ioport_read_table[1][i] = default_ioport_readw;
402 ioport_read_table[2][i] = default_ioport_readl;
404 ioport_write_table[0][i] = default_ioport_writeb;
405 ioport_write_table[1][i] = default_ioport_writew;
406 ioport_write_table[2][i] = default_ioport_writel;
408 ioport_opaque[i] = NULL;
412 /***********************************************************/
414 void cpu_outb(CPUState *env, int addr, int val)
416 LOG_IOPORT("outb: %04x %02x\n", addr, val);
417 ioport_write(0, addr, val);
420 env->last_io_time = cpu_get_time_fast();
424 void cpu_outw(CPUState *env, int addr, int val)
426 LOG_IOPORT("outw: %04x %04x\n", addr, val);
427 ioport_write(1, addr, val);
430 env->last_io_time = cpu_get_time_fast();
434 void cpu_outl(CPUState *env, int addr, int val)
436 LOG_IOPORT("outl: %04x %08x\n", addr, val);
437 ioport_write(2, addr, val);
440 env->last_io_time = cpu_get_time_fast();
444 int cpu_inb(CPUState *env, int addr)
447 val = ioport_read(0, addr);
448 LOG_IOPORT("inb : %04x %02x\n", addr, val);
451 env->last_io_time = cpu_get_time_fast();
456 int cpu_inw(CPUState *env, int addr)
459 val = ioport_read(1, addr);
460 LOG_IOPORT("inw : %04x %04x\n", addr, val);
463 env->last_io_time = cpu_get_time_fast();
468 int cpu_inl(CPUState *env, int addr)
471 val = ioport_read(2, addr);
472 LOG_IOPORT("inl : %04x %08x\n", addr, val);
475 env->last_io_time = cpu_get_time_fast();
480 /***********************************************************/
481 void hw_error(const char *fmt, ...)
487 fprintf(stderr, "qemu: hardware error: ");
488 vfprintf(stderr, fmt, ap);
489 fprintf(stderr, "\n");
490 for(env = first_cpu; env != NULL; env = env->next_cpu) {
491 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
493 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
495 cpu_dump_state(env, stderr, fprintf, 0);
505 static QEMUBalloonEvent *qemu_balloon_event;
506 void *qemu_balloon_event_opaque;
508 void qemu_add_balloon_handler(QEMUBalloonEvent *func, void *opaque)
510 qemu_balloon_event = func;
511 qemu_balloon_event_opaque = opaque;
514 void qemu_balloon(ram_addr_t target)
516 if (qemu_balloon_event)
517 qemu_balloon_event(qemu_balloon_event_opaque, target);
520 ram_addr_t qemu_balloon_status(void)
522 if (qemu_balloon_event)
523 return qemu_balloon_event(qemu_balloon_event_opaque, 0);
527 /***********************************************************/
530 static QEMUPutKBDEvent *qemu_put_kbd_event;
531 static void *qemu_put_kbd_event_opaque;
532 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
533 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
535 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
537 qemu_put_kbd_event_opaque = opaque;
538 qemu_put_kbd_event = func;
541 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
542 void *opaque, int absolute,
545 QEMUPutMouseEntry *s, *cursor;
547 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
549 s->qemu_put_mouse_event = func;
550 s->qemu_put_mouse_event_opaque = opaque;
551 s->qemu_put_mouse_event_absolute = absolute;
552 s->qemu_put_mouse_event_name = qemu_strdup(name);
555 if (!qemu_put_mouse_event_head) {
556 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
560 cursor = qemu_put_mouse_event_head;
561 while (cursor->next != NULL)
562 cursor = cursor->next;
565 qemu_put_mouse_event_current = s;
570 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
572 QEMUPutMouseEntry *prev = NULL, *cursor;
574 if (!qemu_put_mouse_event_head || entry == NULL)
577 cursor = qemu_put_mouse_event_head;
578 while (cursor != NULL && cursor != entry) {
580 cursor = cursor->next;
583 if (cursor == NULL) // does not exist or list empty
585 else if (prev == NULL) { // entry is head
586 qemu_put_mouse_event_head = cursor->next;
587 if (qemu_put_mouse_event_current == entry)
588 qemu_put_mouse_event_current = cursor->next;
589 qemu_free(entry->qemu_put_mouse_event_name);
594 prev->next = entry->next;
596 if (qemu_put_mouse_event_current == entry)
597 qemu_put_mouse_event_current = prev;
599 qemu_free(entry->qemu_put_mouse_event_name);
603 void kbd_put_keycode(int keycode)
605 if (qemu_put_kbd_event) {
606 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
610 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
612 QEMUPutMouseEvent *mouse_event;
613 void *mouse_event_opaque;
616 if (!qemu_put_mouse_event_current) {
621 qemu_put_mouse_event_current->qemu_put_mouse_event;
623 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
626 if (graphic_rotate) {
627 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
630 width = graphic_width - 1;
631 mouse_event(mouse_event_opaque,
632 width - dy, dx, dz, buttons_state);
634 mouse_event(mouse_event_opaque,
635 dx, dy, dz, buttons_state);
639 int kbd_mouse_is_absolute(void)
641 if (!qemu_put_mouse_event_current)
644 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
647 void do_info_mice(void)
649 QEMUPutMouseEntry *cursor;
652 if (!qemu_put_mouse_event_head) {
653 term_printf("No mouse devices connected\n");
657 term_printf("Mouse devices available:\n");
658 cursor = qemu_put_mouse_event_head;
659 while (cursor != NULL) {
660 term_printf("%c Mouse #%d: %s\n",
661 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
662 index, cursor->qemu_put_mouse_event_name);
664 cursor = cursor->next;
668 void do_mouse_set(int index)
670 QEMUPutMouseEntry *cursor;
673 if (!qemu_put_mouse_event_head) {
674 term_printf("No mouse devices connected\n");
678 cursor = qemu_put_mouse_event_head;
679 while (cursor != NULL && index != i) {
681 cursor = cursor->next;
685 qemu_put_mouse_event_current = cursor;
687 term_printf("Mouse at given index not found\n");
690 /* compute with 96 bit intermediate result: (a*b)/c */
691 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
696 #ifdef WORDS_BIGENDIAN
706 rl = (uint64_t)u.l.low * (uint64_t)b;
707 rh = (uint64_t)u.l.high * (uint64_t)b;
710 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
714 /***********************************************************/
715 /* real time host monotonic timer */
717 #define QEMU_TIMER_BASE 1000000000LL
721 static int64_t clock_freq;
723 static void init_get_clock(void)
727 ret = QueryPerformanceFrequency(&freq);
729 fprintf(stderr, "Could not calibrate ticks\n");
732 clock_freq = freq.QuadPart;
735 static int64_t get_clock(void)
738 QueryPerformanceCounter(&ti);
739 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
744 static int use_rt_clock;
746 static void init_get_clock(void)
749 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000)
752 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
759 static int64_t get_clock(void)
761 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000)
764 clock_gettime(CLOCK_MONOTONIC, &ts);
765 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
769 /* XXX: using gettimeofday leads to problems if the date
770 changes, so it should be avoided. */
772 gettimeofday(&tv, NULL);
773 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
778 /* Return the virtual CPU time, based on the instruction counter. */
779 static int64_t cpu_get_icount(void)
782 CPUState *env = cpu_single_env;;
783 icount = qemu_icount;
786 fprintf(stderr, "Bad clock read\n");
787 icount -= (env->icount_decr.u16.low + env->icount_extra);
789 return qemu_icount_bias + (icount << icount_time_shift);
792 /***********************************************************/
793 /* guest cycle counter */
795 static int64_t cpu_ticks_prev;
796 static int64_t cpu_ticks_offset;
797 static int64_t cpu_clock_offset;
798 static int cpu_ticks_enabled;
800 /* return the host CPU cycle counter and handle stop/restart */
801 int64_t cpu_get_ticks(void)
804 return cpu_get_icount();
806 if (!cpu_ticks_enabled) {
807 return cpu_ticks_offset;
810 ticks = cpu_get_real_ticks();
811 if (cpu_ticks_prev > ticks) {
812 /* Note: non increasing ticks may happen if the host uses
814 cpu_ticks_offset += cpu_ticks_prev - ticks;
816 cpu_ticks_prev = ticks;
817 return ticks + cpu_ticks_offset;
821 /* return the host CPU monotonic timer and handle stop/restart */
822 static int64_t cpu_get_clock(void)
825 if (!cpu_ticks_enabled) {
826 return cpu_clock_offset;
829 return ti + cpu_clock_offset;
833 /* enable cpu_get_ticks() */
834 void cpu_enable_ticks(void)
836 if (!cpu_ticks_enabled) {
837 cpu_ticks_offset -= cpu_get_real_ticks();
838 cpu_clock_offset -= get_clock();
839 cpu_ticks_enabled = 1;
843 /* disable cpu_get_ticks() : the clock is stopped. You must not call
844 cpu_get_ticks() after that. */
845 void cpu_disable_ticks(void)
847 if (cpu_ticks_enabled) {
848 cpu_ticks_offset = cpu_get_ticks();
849 cpu_clock_offset = cpu_get_clock();
850 cpu_ticks_enabled = 0;
854 /***********************************************************/
857 #define QEMU_TIMER_REALTIME 0
858 #define QEMU_TIMER_VIRTUAL 1
862 /* XXX: add frequency */
870 struct QEMUTimer *next;
873 struct qemu_alarm_timer {
877 int (*start)(struct qemu_alarm_timer *t);
878 void (*stop)(struct qemu_alarm_timer *t);
879 void (*rearm)(struct qemu_alarm_timer *t);
883 #define ALARM_FLAG_DYNTICKS 0x1
884 #define ALARM_FLAG_EXPIRED 0x2
886 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
888 return t->flags & ALARM_FLAG_DYNTICKS;
891 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
893 if (!alarm_has_dynticks(t))
899 /* TODO: MIN_TIMER_REARM_US should be optimized */
900 #define MIN_TIMER_REARM_US 250
902 static struct qemu_alarm_timer *alarm_timer;
904 static int alarm_timer_rfd, alarm_timer_wfd;
909 struct qemu_alarm_win32 {
913 } alarm_win32_data = {0, NULL, -1};
915 static int win32_start_timer(struct qemu_alarm_timer *t);
916 static void win32_stop_timer(struct qemu_alarm_timer *t);
917 static void win32_rearm_timer(struct qemu_alarm_timer *t);
921 static int unix_start_timer(struct qemu_alarm_timer *t);
922 static void unix_stop_timer(struct qemu_alarm_timer *t);
926 static int dynticks_start_timer(struct qemu_alarm_timer *t);
927 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
928 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
930 static int hpet_start_timer(struct qemu_alarm_timer *t);
931 static void hpet_stop_timer(struct qemu_alarm_timer *t);
933 static int rtc_start_timer(struct qemu_alarm_timer *t);
934 static void rtc_stop_timer(struct qemu_alarm_timer *t);
936 #endif /* __linux__ */
940 /* Correlation between real and virtual time is always going to be
941 fairly approximate, so ignore small variation.
942 When the guest is idle real and virtual time will be aligned in
944 #define ICOUNT_WOBBLE (QEMU_TIMER_BASE / 10)
946 static void icount_adjust(void)
951 static int64_t last_delta;
952 /* If the VM is not running, then do nothing. */
956 cur_time = cpu_get_clock();
957 cur_icount = qemu_get_clock(vm_clock);
958 delta = cur_icount - cur_time;
959 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
961 && last_delta + ICOUNT_WOBBLE < delta * 2
962 && icount_time_shift > 0) {
963 /* The guest is getting too far ahead. Slow time down. */
967 && last_delta - ICOUNT_WOBBLE > delta * 2
968 && icount_time_shift < MAX_ICOUNT_SHIFT) {
969 /* The guest is getting too far behind. Speed time up. */
973 qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
976 static void icount_adjust_rt(void * opaque)
978 qemu_mod_timer(icount_rt_timer,
979 qemu_get_clock(rt_clock) + 1000);
983 static void icount_adjust_vm(void * opaque)
985 qemu_mod_timer(icount_vm_timer,
986 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
990 static void init_icount_adjust(void)
992 /* Have both realtime and virtual time triggers for speed adjustment.
993 The realtime trigger catches emulated time passing too slowly,
994 the virtual time trigger catches emulated time passing too fast.
995 Realtime triggers occur even when idle, so use them less frequently
997 icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
998 qemu_mod_timer(icount_rt_timer,
999 qemu_get_clock(rt_clock) + 1000);
1000 icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
1001 qemu_mod_timer(icount_vm_timer,
1002 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
1005 static struct qemu_alarm_timer alarm_timers[] = {
1008 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
1009 dynticks_stop_timer, dynticks_rearm_timer, NULL},
1010 /* HPET - if available - is preferred */
1011 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
1012 /* ...otherwise try RTC */
1013 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
1015 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
1017 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
1018 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
1019 {"win32", 0, win32_start_timer,
1020 win32_stop_timer, NULL, &alarm_win32_data},
1025 static void show_available_alarms(void)
1029 printf("Available alarm timers, in order of precedence:\n");
1030 for (i = 0; alarm_timers[i].name; i++)
1031 printf("%s\n", alarm_timers[i].name);
1034 static void configure_alarms(char const *opt)
1038 int count = ARRAY_SIZE(alarm_timers) - 1;
1041 struct qemu_alarm_timer tmp;
1043 if (!strcmp(opt, "?")) {
1044 show_available_alarms();
1050 /* Reorder the array */
1051 name = strtok(arg, ",");
1053 for (i = 0; i < count && alarm_timers[i].name; i++) {
1054 if (!strcmp(alarm_timers[i].name, name))
1059 fprintf(stderr, "Unknown clock %s\n", name);
1068 tmp = alarm_timers[i];
1069 alarm_timers[i] = alarm_timers[cur];
1070 alarm_timers[cur] = tmp;
1074 name = strtok(NULL, ",");
1080 /* Disable remaining timers */
1081 for (i = cur; i < count; i++)
1082 alarm_timers[i].name = NULL;
1084 show_available_alarms();
1089 QEMUClock *rt_clock;
1090 QEMUClock *vm_clock;
1092 static QEMUTimer *active_timers[2];
1094 static QEMUClock *qemu_new_clock(int type)
1097 clock = qemu_mallocz(sizeof(QEMUClock));
1102 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
1106 ts = qemu_mallocz(sizeof(QEMUTimer));
1109 ts->opaque = opaque;
1113 void qemu_free_timer(QEMUTimer *ts)
1118 /* stop a timer, but do not dealloc it */
1119 void qemu_del_timer(QEMUTimer *ts)
1123 /* NOTE: this code must be signal safe because
1124 qemu_timer_expired() can be called from a signal. */
1125 pt = &active_timers[ts->clock->type];
1138 /* modify the current timer so that it will be fired when current_time
1139 >= expire_time. The corresponding callback will be called. */
1140 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
1146 /* add the timer in the sorted list */
1147 /* NOTE: this code must be signal safe because
1148 qemu_timer_expired() can be called from a signal. */
1149 pt = &active_timers[ts->clock->type];
1154 if (t->expire_time > expire_time)
1158 ts->expire_time = expire_time;
1162 /* Rearm if necessary */
1163 if (pt == &active_timers[ts->clock->type]) {
1164 if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0) {
1165 qemu_rearm_alarm_timer(alarm_timer);
1167 /* Interrupt execution to force deadline recalculation. */
1168 if (use_icount && cpu_single_env) {
1169 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
1174 int qemu_timer_pending(QEMUTimer *ts)
1177 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1184 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1188 return (timer_head->expire_time <= current_time);
1191 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1197 if (!ts || ts->expire_time > current_time)
1199 /* remove timer from the list before calling the callback */
1200 *ptimer_head = ts->next;
1203 /* run the callback (the timer list can be modified) */
1208 int64_t qemu_get_clock(QEMUClock *clock)
1210 switch(clock->type) {
1211 case QEMU_TIMER_REALTIME:
1212 return get_clock() / 1000000;
1214 case QEMU_TIMER_VIRTUAL:
1216 return cpu_get_icount();
1218 return cpu_get_clock();
1223 static void init_timers(void)
1226 ticks_per_sec = QEMU_TIMER_BASE;
1227 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1228 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1232 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1234 uint64_t expire_time;
1236 if (qemu_timer_pending(ts)) {
1237 expire_time = ts->expire_time;
1241 qemu_put_be64(f, expire_time);
1244 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1246 uint64_t expire_time;
1248 expire_time = qemu_get_be64(f);
1249 if (expire_time != -1) {
1250 qemu_mod_timer(ts, expire_time);
1256 static void timer_save(QEMUFile *f, void *opaque)
1258 if (cpu_ticks_enabled) {
1259 hw_error("cannot save state if virtual timers are running");
1261 qemu_put_be64(f, cpu_ticks_offset);
1262 qemu_put_be64(f, ticks_per_sec);
1263 qemu_put_be64(f, cpu_clock_offset);
1266 static int timer_load(QEMUFile *f, void *opaque, int version_id)
1268 if (version_id != 1 && version_id != 2)
1270 if (cpu_ticks_enabled) {
1273 cpu_ticks_offset=qemu_get_be64(f);
1274 ticks_per_sec=qemu_get_be64(f);
1275 if (version_id == 2) {
1276 cpu_clock_offset=qemu_get_be64(f);
1282 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1283 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
1285 static void host_alarm_handler(int host_signum)
1289 #define DISP_FREQ 1000
1291 static int64_t delta_min = INT64_MAX;
1292 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1294 ti = qemu_get_clock(vm_clock);
1295 if (last_clock != 0) {
1296 delta = ti - last_clock;
1297 if (delta < delta_min)
1299 if (delta > delta_max)
1302 if (++count == DISP_FREQ) {
1303 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1304 muldiv64(delta_min, 1000000, ticks_per_sec),
1305 muldiv64(delta_max, 1000000, ticks_per_sec),
1306 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1307 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1309 delta_min = INT64_MAX;
1317 if (alarm_has_dynticks(alarm_timer) ||
1319 qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1320 qemu_get_clock(vm_clock))) ||
1321 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1322 qemu_get_clock(rt_clock))) {
1323 CPUState *env = next_cpu;
1326 struct qemu_alarm_win32 *data = ((struct qemu_alarm_timer*)dwUser)->priv;
1327 SetEvent(data->host_alarm);
1329 static const char byte = 0;
1330 write(alarm_timer_wfd, &byte, sizeof(byte));
1332 alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1335 /* stop the currently executing cpu because a timer occured */
1336 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
1338 if (env->kqemu_enabled) {
1339 kqemu_cpu_interrupt(env);
1347 static int64_t qemu_next_deadline(void)
1351 if (active_timers[QEMU_TIMER_VIRTUAL]) {
1352 delta = active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1353 qemu_get_clock(vm_clock);
1355 /* To avoid problems with overflow limit this to 2^32. */
1365 #if defined(__linux__) || defined(_WIN32)
1366 static uint64_t qemu_next_deadline_dyntick(void)
1374 delta = (qemu_next_deadline() + 999) / 1000;
1376 if (active_timers[QEMU_TIMER_REALTIME]) {
1377 rtdelta = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1378 qemu_get_clock(rt_clock))*1000;
1379 if (rtdelta < delta)
1383 if (delta < MIN_TIMER_REARM_US)
1384 delta = MIN_TIMER_REARM_US;
1392 /* Sets a specific flag */
1393 static int fcntl_setfl(int fd, int flag)
1397 flags = fcntl(fd, F_GETFL);
1401 if (fcntl(fd, F_SETFL, flags | flag) == -1)
1407 #if defined(__linux__)
1409 #define RTC_FREQ 1024
1411 static void enable_sigio_timer(int fd)
1413 struct sigaction act;
1416 sigfillset(&act.sa_mask);
1418 act.sa_handler = host_alarm_handler;
1420 sigaction(SIGIO, &act, NULL);
1421 fcntl_setfl(fd, O_ASYNC);
1422 fcntl(fd, F_SETOWN, getpid());
1425 static int hpet_start_timer(struct qemu_alarm_timer *t)
1427 struct hpet_info info;
1430 fd = open("/dev/hpet", O_RDONLY);
1435 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1437 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1438 "error, but for better emulation accuracy type:\n"
1439 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1443 /* Check capabilities */
1444 r = ioctl(fd, HPET_INFO, &info);
1448 /* Enable periodic mode */
1449 r = ioctl(fd, HPET_EPI, 0);
1450 if (info.hi_flags && (r < 0))
1453 /* Enable interrupt */
1454 r = ioctl(fd, HPET_IE_ON, 0);
1458 enable_sigio_timer(fd);
1459 t->priv = (void *)(long)fd;
1467 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1469 int fd = (long)t->priv;
1474 static int rtc_start_timer(struct qemu_alarm_timer *t)
1477 unsigned long current_rtc_freq = 0;
1479 TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1482 ioctl(rtc_fd, RTC_IRQP_READ, ¤t_rtc_freq);
1483 if (current_rtc_freq != RTC_FREQ &&
1484 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1485 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1486 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1487 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1490 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1496 enable_sigio_timer(rtc_fd);
1498 t->priv = (void *)(long)rtc_fd;
1503 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1505 int rtc_fd = (long)t->priv;
1510 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1514 struct sigaction act;
1516 sigfillset(&act.sa_mask);
1518 act.sa_handler = host_alarm_handler;
1520 sigaction(SIGALRM, &act, NULL);
1522 ev.sigev_value.sival_int = 0;
1523 ev.sigev_notify = SIGEV_SIGNAL;
1524 ev.sigev_signo = SIGALRM;
1526 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1527 perror("timer_create");
1529 /* disable dynticks */
1530 fprintf(stderr, "Dynamic Ticks disabled\n");
1535 t->priv = (void *)(long)host_timer;
1540 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1542 timer_t host_timer = (timer_t)(long)t->priv;
1544 timer_delete(host_timer);
1547 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1549 timer_t host_timer = (timer_t)(long)t->priv;
1550 struct itimerspec timeout;
1551 int64_t nearest_delta_us = INT64_MAX;
1554 if (!active_timers[QEMU_TIMER_REALTIME] &&
1555 !active_timers[QEMU_TIMER_VIRTUAL])
1558 nearest_delta_us = qemu_next_deadline_dyntick();
1560 /* check whether a timer is already running */
1561 if (timer_gettime(host_timer, &timeout)) {
1563 fprintf(stderr, "Internal timer error: aborting\n");
1566 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1567 if (current_us && current_us <= nearest_delta_us)
1570 timeout.it_interval.tv_sec = 0;
1571 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1572 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1573 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1574 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1576 fprintf(stderr, "Internal timer error: aborting\n");
1581 #endif /* defined(__linux__) */
1583 static int unix_start_timer(struct qemu_alarm_timer *t)
1585 struct sigaction act;
1586 struct itimerval itv;
1590 sigfillset(&act.sa_mask);
1592 act.sa_handler = host_alarm_handler;
1594 sigaction(SIGALRM, &act, NULL);
1596 itv.it_interval.tv_sec = 0;
1597 /* for i386 kernel 2.6 to get 1 ms */
1598 itv.it_interval.tv_usec = 999;
1599 itv.it_value.tv_sec = 0;
1600 itv.it_value.tv_usec = 10 * 1000;
1602 err = setitimer(ITIMER_REAL, &itv, NULL);
1609 static void unix_stop_timer(struct qemu_alarm_timer *t)
1611 struct itimerval itv;
1613 memset(&itv, 0, sizeof(itv));
1614 setitimer(ITIMER_REAL, &itv, NULL);
1617 #endif /* !defined(_WIN32) */
1619 static void try_to_rearm_timer(void *opaque)
1621 struct qemu_alarm_timer *t = opaque;
1625 /* Drain the notify pipe */
1628 len = read(alarm_timer_rfd, buffer, sizeof(buffer));
1629 } while ((len == -1 && errno == EINTR) || len > 0);
1632 if (t->flags & ALARM_FLAG_EXPIRED) {
1633 alarm_timer->flags &= ~ALARM_FLAG_EXPIRED;
1634 qemu_rearm_alarm_timer(alarm_timer);
1640 static int win32_start_timer(struct qemu_alarm_timer *t)
1643 struct qemu_alarm_win32 *data = t->priv;
1646 data->host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1647 if (!data->host_alarm) {
1648 perror("Failed CreateEvent");
1652 memset(&tc, 0, sizeof(tc));
1653 timeGetDevCaps(&tc, sizeof(tc));
1655 if (data->period < tc.wPeriodMin)
1656 data->period = tc.wPeriodMin;
1658 timeBeginPeriod(data->period);
1660 flags = TIME_CALLBACK_FUNCTION;
1661 if (alarm_has_dynticks(t))
1662 flags |= TIME_ONESHOT;
1664 flags |= TIME_PERIODIC;
1666 data->timerId = timeSetEvent(1, // interval (ms)
1667 data->period, // resolution
1668 host_alarm_handler, // function
1669 (DWORD)t, // parameter
1672 if (!data->timerId) {
1673 perror("Failed to initialize win32 alarm timer");
1675 timeEndPeriod(data->period);
1676 CloseHandle(data->host_alarm);
1680 qemu_add_wait_object(data->host_alarm, try_to_rearm_timer, t);
1685 static void win32_stop_timer(struct qemu_alarm_timer *t)
1687 struct qemu_alarm_win32 *data = t->priv;
1689 timeKillEvent(data->timerId);
1690 timeEndPeriod(data->period);
1692 CloseHandle(data->host_alarm);
1695 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1697 struct qemu_alarm_win32 *data = t->priv;
1698 uint64_t nearest_delta_us;
1700 if (!active_timers[QEMU_TIMER_REALTIME] &&
1701 !active_timers[QEMU_TIMER_VIRTUAL])
1704 nearest_delta_us = qemu_next_deadline_dyntick();
1705 nearest_delta_us /= 1000;
1707 timeKillEvent(data->timerId);
1709 data->timerId = timeSetEvent(1,
1713 TIME_ONESHOT | TIME_PERIODIC);
1715 if (!data->timerId) {
1716 perror("Failed to re-arm win32 alarm timer");
1718 timeEndPeriod(data->period);
1719 CloseHandle(data->host_alarm);
1726 static int init_timer_alarm(void)
1728 struct qemu_alarm_timer *t = NULL;
1738 err = fcntl_setfl(fds[0], O_NONBLOCK);
1742 err = fcntl_setfl(fds[1], O_NONBLOCK);
1746 alarm_timer_rfd = fds[0];
1747 alarm_timer_wfd = fds[1];
1750 for (i = 0; alarm_timers[i].name; i++) {
1751 t = &alarm_timers[i];
1764 qemu_set_fd_handler2(alarm_timer_rfd, NULL,
1765 try_to_rearm_timer, NULL, t);
1780 static void quit_timers(void)
1782 alarm_timer->stop(alarm_timer);
1786 /***********************************************************/
1787 /* host time/date access */
1788 void qemu_get_timedate(struct tm *tm, int offset)
1795 if (rtc_date_offset == -1) {
1799 ret = localtime(&ti);
1801 ti -= rtc_date_offset;
1805 memcpy(tm, ret, sizeof(struct tm));
1808 int qemu_timedate_diff(struct tm *tm)
1812 if (rtc_date_offset == -1)
1814 seconds = mktimegm(tm);
1816 seconds = mktime(tm);
1818 seconds = mktimegm(tm) + rtc_date_offset;
1820 return seconds - time(NULL);
1824 static void socket_cleanup(void)
1829 static int socket_init(void)
1834 ret = WSAStartup(MAKEWORD(2,2), &Data);
1836 err = WSAGetLastError();
1837 fprintf(stderr, "WSAStartup: %d\n", err);
1840 atexit(socket_cleanup);
1845 const char *get_opt_name(char *buf, int buf_size, const char *p)
1850 while (*p != '\0' && *p != '=') {
1851 if (q && (q - buf) < buf_size - 1)
1861 const char *get_opt_value(char *buf, int buf_size, const char *p)
1866 while (*p != '\0') {
1868 if (*(p + 1) != ',')
1872 if (q && (q - buf) < buf_size - 1)
1882 int get_param_value(char *buf, int buf_size,
1883 const char *tag, const char *str)
1890 p = get_opt_name(option, sizeof(option), p);
1894 if (!strcmp(tag, option)) {
1895 (void)get_opt_value(buf, buf_size, p);
1898 p = get_opt_value(NULL, 0, p);
1907 int check_params(char *buf, int buf_size,
1908 const char * const *params, const char *str)
1915 p = get_opt_name(buf, buf_size, p);
1919 for(i = 0; params[i] != NULL; i++)
1920 if (!strcmp(params[i], buf))
1922 if (params[i] == NULL)
1924 p = get_opt_value(NULL, 0, p);
1932 /***********************************************************/
1933 /* Bluetooth support */
1936 static struct HCIInfo *hci_table[MAX_NICS];
1938 static struct bt_vlan_s {
1939 struct bt_scatternet_s net;
1941 struct bt_vlan_s *next;
1944 /* find or alloc a new bluetooth "VLAN" */
1945 static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
1947 struct bt_vlan_s **pvlan, *vlan;
1948 for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
1952 vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
1954 pvlan = &first_bt_vlan;
1955 while (*pvlan != NULL)
1956 pvlan = &(*pvlan)->next;
1961 static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
1965 static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
1970 static struct HCIInfo null_hci = {
1971 .cmd_send = null_hci_send,
1972 .sco_send = null_hci_send,
1973 .acl_send = null_hci_send,
1974 .bdaddr_set = null_hci_addr_set,
1977 struct HCIInfo *qemu_next_hci(void)
1979 if (cur_hci == nb_hcis)
1982 return hci_table[cur_hci++];
1985 static struct HCIInfo *hci_init(const char *str)
1988 struct bt_scatternet_s *vlan = 0;
1990 if (!strcmp(str, "null"))
1993 else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
1995 return bt_host_hci(str[4] ? str + 5 : "hci0");
1996 else if (!strncmp(str, "hci", 3)) {
1999 if (!strncmp(str + 3, ",vlan=", 6)) {
2000 vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
2005 vlan = qemu_find_bt_vlan(0);
2007 return bt_new_hci(vlan);
2010 fprintf(stderr, "qemu: Unknown bluetooth HCI `%s'.\n", str);
2015 static int bt_hci_parse(const char *str)
2017 struct HCIInfo *hci;
2020 if (nb_hcis >= MAX_NICS) {
2021 fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
2025 hci = hci_init(str);
2034 bdaddr.b[5] = 0x56 + nb_hcis;
2035 hci->bdaddr_set(hci, bdaddr.b);
2037 hci_table[nb_hcis++] = hci;
2042 static void bt_vhci_add(int vlan_id)
2044 struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
2047 fprintf(stderr, "qemu: warning: adding a VHCI to "
2048 "an empty scatternet %i\n", vlan_id);
2050 bt_vhci_init(bt_new_hci(vlan));
2053 static struct bt_device_s *bt_device_add(const char *opt)
2055 struct bt_scatternet_s *vlan;
2057 char *endp = strstr(opt, ",vlan=");
2058 int len = (endp ? endp - opt : strlen(opt)) + 1;
2061 pstrcpy(devname, MIN(sizeof(devname), len), opt);
2064 vlan_id = strtol(endp + 6, &endp, 0);
2066 fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
2071 vlan = qemu_find_bt_vlan(vlan_id);
2074 fprintf(stderr, "qemu: warning: adding a slave device to "
2075 "an empty scatternet %i\n", vlan_id);
2077 if (!strcmp(devname, "keyboard"))
2078 return bt_keyboard_init(vlan);
2080 fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
2084 static int bt_parse(const char *opt)
2086 const char *endp, *p;
2089 if (strstart(opt, "hci", &endp)) {
2090 if (!*endp || *endp == ',') {
2092 if (!strstart(endp, ",vlan=", 0))
2095 return bt_hci_parse(opt);
2097 } else if (strstart(opt, "vhci", &endp)) {
2098 if (!*endp || *endp == ',') {
2100 if (strstart(endp, ",vlan=", &p)) {
2101 vlan = strtol(p, (char **) &endp, 0);
2103 fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
2107 fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
2116 } else if (strstart(opt, "device:", &endp))
2117 return !bt_device_add(endp);
2119 fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
2123 /***********************************************************/
2124 /* QEMU Block devices */
2126 #define HD_ALIAS "index=%d,media=disk"
2128 #define CDROM_ALIAS "index=1,media=cdrom"
2130 #define CDROM_ALIAS "index=2,media=cdrom"
2132 #define FD_ALIAS "index=%d,if=floppy"
2133 #define PFLASH_ALIAS "if=pflash"
2134 #define MTD_ALIAS "if=mtd"
2135 #define SD_ALIAS "index=0,if=sd"
2137 static int drive_opt_get_free_idx(void)
2141 for (index = 0; index < MAX_DRIVES; index++)
2142 if (!drives_opt[index].used) {
2143 drives_opt[index].used = 1;
2150 static int drive_get_free_idx(void)
2154 for (index = 0; index < MAX_DRIVES; index++)
2155 if (!drives_table[index].used) {
2156 drives_table[index].used = 1;
2163 int drive_add(const char *file, const char *fmt, ...)
2166 int index = drive_opt_get_free_idx();
2168 if (nb_drives_opt >= MAX_DRIVES || index == -1) {
2169 fprintf(stderr, "qemu: too many drives\n");
2173 drives_opt[index].file = file;
2175 vsnprintf(drives_opt[index].opt,
2176 sizeof(drives_opt[0].opt), fmt, ap);
2183 void drive_remove(int index)
2185 drives_opt[index].used = 0;
2189 int drive_get_index(BlockInterfaceType type, int bus, int unit)
2193 /* seek interface, bus and unit */
2195 for (index = 0; index < MAX_DRIVES; index++)
2196 if (drives_table[index].type == type &&
2197 drives_table[index].bus == bus &&
2198 drives_table[index].unit == unit &&
2199 drives_table[index].used)
2205 int drive_get_max_bus(BlockInterfaceType type)
2211 for (index = 0; index < nb_drives; index++) {
2212 if(drives_table[index].type == type &&
2213 drives_table[index].bus > max_bus)
2214 max_bus = drives_table[index].bus;
2219 const char *drive_get_serial(BlockDriverState *bdrv)
2223 for (index = 0; index < nb_drives; index++)
2224 if (drives_table[index].bdrv == bdrv)
2225 return drives_table[index].serial;
2230 BlockInterfaceErrorAction drive_get_onerror(BlockDriverState *bdrv)
2234 for (index = 0; index < nb_drives; index++)
2235 if (drives_table[index].bdrv == bdrv)
2236 return drives_table[index].onerror;
2238 return BLOCK_ERR_REPORT;
2241 static void bdrv_format_print(void *opaque, const char *name)
2243 fprintf(stderr, " %s", name);
2246 void drive_uninit(BlockDriverState *bdrv)
2250 for (i = 0; i < MAX_DRIVES; i++)
2251 if (drives_table[i].bdrv == bdrv) {
2252 drives_table[i].bdrv = NULL;
2253 drives_table[i].used = 0;
2254 drive_remove(drives_table[i].drive_opt_idx);
2260 int drive_init(struct drive_opt *arg, int snapshot, void *opaque)
2266 const char *mediastr = "";
2267 BlockInterfaceType type;
2268 enum { MEDIA_DISK, MEDIA_CDROM } media;
2269 int bus_id, unit_id;
2270 int cyls, heads, secs, translation;
2271 BlockDriverState *bdrv;
2272 BlockDriver *drv = NULL;
2273 QEMUMachine *machine = opaque;
2277 int bdrv_flags, onerror;
2278 int drives_table_idx;
2279 char *str = arg->opt;
2280 static const char * const params[] = { "bus", "unit", "if", "index",
2281 "cyls", "heads", "secs", "trans",
2282 "media", "snapshot", "file",
2283 "cache", "format", "serial", "werror",
2286 if (check_params(buf, sizeof(buf), params, str) < 0) {
2287 fprintf(stderr, "qemu: unknown parameter '%s' in '%s'\n",
2293 cyls = heads = secs = 0;
2296 translation = BIOS_ATA_TRANSLATION_AUTO;
2300 if (machine->use_scsi) {
2302 max_devs = MAX_SCSI_DEVS;
2303 pstrcpy(devname, sizeof(devname), "scsi");
2306 max_devs = MAX_IDE_DEVS;
2307 pstrcpy(devname, sizeof(devname), "ide");
2311 /* extract parameters */
2313 if (get_param_value(buf, sizeof(buf), "bus", str)) {
2314 bus_id = strtol(buf, NULL, 0);
2316 fprintf(stderr, "qemu: '%s' invalid bus id\n", str);
2321 if (get_param_value(buf, sizeof(buf), "unit", str)) {
2322 unit_id = strtol(buf, NULL, 0);
2324 fprintf(stderr, "qemu: '%s' invalid unit id\n", str);
2329 if (get_param_value(buf, sizeof(buf), "if", str)) {
2330 pstrcpy(devname, sizeof(devname), buf);
2331 if (!strcmp(buf, "ide")) {
2333 max_devs = MAX_IDE_DEVS;
2334 } else if (!strcmp(buf, "scsi")) {
2336 max_devs = MAX_SCSI_DEVS;
2337 } else if (!strcmp(buf, "floppy")) {
2340 } else if (!strcmp(buf, "pflash")) {
2343 } else if (!strcmp(buf, "mtd")) {
2346 } else if (!strcmp(buf, "sd")) {
2349 } else if (!strcmp(buf, "virtio")) {
2353 fprintf(stderr, "qemu: '%s' unsupported bus type '%s'\n", str, buf);
2358 if (get_param_value(buf, sizeof(buf), "index", str)) {
2359 index = strtol(buf, NULL, 0);
2361 fprintf(stderr, "qemu: '%s' invalid index\n", str);
2366 if (get_param_value(buf, sizeof(buf), "cyls", str)) {
2367 cyls = strtol(buf, NULL, 0);
2370 if (get_param_value(buf, sizeof(buf), "heads", str)) {
2371 heads = strtol(buf, NULL, 0);
2374 if (get_param_value(buf, sizeof(buf), "secs", str)) {
2375 secs = strtol(buf, NULL, 0);
2378 if (cyls || heads || secs) {
2379 if (cyls < 1 || cyls > 16383) {
2380 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", str);
2383 if (heads < 1 || heads > 16) {
2384 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", str);
2387 if (secs < 1 || secs > 63) {
2388 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", str);
2393 if (get_param_value(buf, sizeof(buf), "trans", str)) {
2396 "qemu: '%s' trans must be used with cyls,heads and secs\n",
2400 if (!strcmp(buf, "none"))
2401 translation = BIOS_ATA_TRANSLATION_NONE;
2402 else if (!strcmp(buf, "lba"))
2403 translation = BIOS_ATA_TRANSLATION_LBA;
2404 else if (!strcmp(buf, "auto"))
2405 translation = BIOS_ATA_TRANSLATION_AUTO;
2407 fprintf(stderr, "qemu: '%s' invalid translation type\n", str);
2412 if (get_param_value(buf, sizeof(buf), "media", str)) {
2413 if (!strcmp(buf, "disk")) {
2415 } else if (!strcmp(buf, "cdrom")) {
2416 if (cyls || secs || heads) {
2418 "qemu: '%s' invalid physical CHS format\n", str);
2421 media = MEDIA_CDROM;
2423 fprintf(stderr, "qemu: '%s' invalid media\n", str);
2428 if (get_param_value(buf, sizeof(buf), "snapshot", str)) {
2429 if (!strcmp(buf, "on"))
2431 else if (!strcmp(buf, "off"))
2434 fprintf(stderr, "qemu: '%s' invalid snapshot option\n", str);
2439 if (get_param_value(buf, sizeof(buf), "cache", str)) {
2440 if (!strcmp(buf, "off") || !strcmp(buf, "none"))
2442 else if (!strcmp(buf, "writethrough"))
2444 else if (!strcmp(buf, "writeback"))
2447 fprintf(stderr, "qemu: invalid cache option\n");
2452 if (get_param_value(buf, sizeof(buf), "format", str)) {
2453 if (strcmp(buf, "?") == 0) {
2454 fprintf(stderr, "qemu: Supported formats:");
2455 bdrv_iterate_format(bdrv_format_print, NULL);
2456 fprintf(stderr, "\n");
2459 drv = bdrv_find_format(buf);
2461 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
2466 if (arg->file == NULL)
2467 get_param_value(file, sizeof(file), "file", str);
2469 pstrcpy(file, sizeof(file), arg->file);
2471 if (!get_param_value(serial, sizeof(serial), "serial", str))
2472 memset(serial, 0, sizeof(serial));
2474 onerror = BLOCK_ERR_REPORT;
2475 if (get_param_value(buf, sizeof(serial), "werror", str)) {
2476 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
2477 fprintf(stderr, "werror is no supported by this format\n");
2480 if (!strcmp(buf, "ignore"))
2481 onerror = BLOCK_ERR_IGNORE;
2482 else if (!strcmp(buf, "enospc"))
2483 onerror = BLOCK_ERR_STOP_ENOSPC;
2484 else if (!strcmp(buf, "stop"))
2485 onerror = BLOCK_ERR_STOP_ANY;
2486 else if (!strcmp(buf, "report"))
2487 onerror = BLOCK_ERR_REPORT;
2489 fprintf(stderr, "qemu: '%s' invalid write error action\n", buf);
2494 /* compute bus and unit according index */
2497 if (bus_id != 0 || unit_id != -1) {
2499 "qemu: '%s' index cannot be used with bus and unit\n", str);
2507 unit_id = index % max_devs;
2508 bus_id = index / max_devs;
2512 /* if user doesn't specify a unit_id,
2513 * try to find the first free
2516 if (unit_id == -1) {
2518 while (drive_get_index(type, bus_id, unit_id) != -1) {
2520 if (max_devs && unit_id >= max_devs) {
2521 unit_id -= max_devs;
2529 if (max_devs && unit_id >= max_devs) {
2530 fprintf(stderr, "qemu: '%s' unit %d too big (max is %d)\n",
2531 str, unit_id, max_devs - 1);
2536 * ignore multiple definitions
2539 if (drive_get_index(type, bus_id, unit_id) != -1)
2544 if (type == IF_IDE || type == IF_SCSI)
2545 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
2547 snprintf(buf, sizeof(buf), "%s%i%s%i",
2548 devname, bus_id, mediastr, unit_id);
2550 snprintf(buf, sizeof(buf), "%s%s%i",
2551 devname, mediastr, unit_id);
2552 bdrv = bdrv_new(buf);
2553 drives_table_idx = drive_get_free_idx();
2554 drives_table[drives_table_idx].bdrv = bdrv;
2555 drives_table[drives_table_idx].type = type;
2556 drives_table[drives_table_idx].bus = bus_id;
2557 drives_table[drives_table_idx].unit = unit_id;
2558 drives_table[drives_table_idx].onerror = onerror;
2559 drives_table[drives_table_idx].drive_opt_idx = arg - drives_opt;
2560 strncpy(drives_table[nb_drives].serial, serial, sizeof(serial));
2569 bdrv_set_geometry_hint(bdrv, cyls, heads, secs);
2570 bdrv_set_translation_hint(bdrv, translation);
2574 bdrv_set_type_hint(bdrv, BDRV_TYPE_CDROM);
2579 /* FIXME: This isn't really a floppy, but it's a reasonable
2582 bdrv_set_type_hint(bdrv, BDRV_TYPE_FLOPPY);
2593 bdrv_flags |= BDRV_O_SNAPSHOT;
2594 cache = 2; /* always use write-back with snapshot */
2596 if (cache == 0) /* no caching */
2597 bdrv_flags |= BDRV_O_NOCACHE;
2598 else if (cache == 2) /* write-back */
2599 bdrv_flags |= BDRV_O_CACHE_WB;
2600 else if (cache == 3) /* not specified */
2601 bdrv_flags |= BDRV_O_CACHE_DEF;
2602 if (bdrv_open2(bdrv, file, bdrv_flags, drv) < 0 || qemu_key_check(bdrv, file)) {
2603 fprintf(stderr, "qemu: could not open disk image %s\n",
2607 return drives_table_idx;
2610 /***********************************************************/
2613 static USBPort *used_usb_ports;
2614 static USBPort *free_usb_ports;
2616 /* ??? Maybe change this to register a hub to keep track of the topology. */
2617 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
2618 usb_attachfn attach)
2620 port->opaque = opaque;
2621 port->index = index;
2622 port->attach = attach;
2623 port->next = free_usb_ports;
2624 free_usb_ports = port;
2627 int usb_device_add_dev(USBDevice *dev)
2631 /* Find a USB port to add the device to. */
2632 port = free_usb_ports;
2636 /* Create a new hub and chain it on. */
2637 free_usb_ports = NULL;
2638 port->next = used_usb_ports;
2639 used_usb_ports = port;
2641 hub = usb_hub_init(VM_USB_HUB_SIZE);
2642 usb_attach(port, hub);
2643 port = free_usb_ports;
2646 free_usb_ports = port->next;
2647 port->next = used_usb_ports;
2648 used_usb_ports = port;
2649 usb_attach(port, dev);
2653 static int usb_device_add(const char *devname)
2658 if (!free_usb_ports)
2661 if (strstart(devname, "host:", &p)) {
2662 dev = usb_host_device_open(p);
2663 } else if (!strcmp(devname, "mouse")) {
2664 dev = usb_mouse_init();
2665 } else if (!strcmp(devname, "tablet")) {
2666 dev = usb_tablet_init();
2667 } else if (!strcmp(devname, "keyboard")) {
2668 dev = usb_keyboard_init();
2669 } else if (strstart(devname, "disk:", &p)) {
2670 dev = usb_msd_init(p);
2671 } else if (!strcmp(devname, "wacom-tablet")) {
2672 dev = usb_wacom_init();
2673 } else if (strstart(devname, "serial:", &p)) {
2674 dev = usb_serial_init(p);
2675 #ifdef CONFIG_BRLAPI
2676 } else if (!strcmp(devname, "braille")) {
2677 dev = usb_baum_init();
2679 } else if (strstart(devname, "net:", &p)) {
2682 if (net_client_init("nic", p) < 0)
2684 nd_table[nic].model = "usb";
2685 dev = usb_net_init(&nd_table[nic]);
2686 } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
2687 dev = usb_bt_init(devname[2] ? hci_init(p) :
2688 bt_new_hci(qemu_find_bt_vlan(0)));
2695 return usb_device_add_dev(dev);
2698 int usb_device_del_addr(int bus_num, int addr)
2704 if (!used_usb_ports)
2710 lastp = &used_usb_ports;
2711 port = used_usb_ports;
2712 while (port && port->dev->addr != addr) {
2713 lastp = &port->next;
2721 *lastp = port->next;
2722 usb_attach(port, NULL);
2723 dev->handle_destroy(dev);
2724 port->next = free_usb_ports;
2725 free_usb_ports = port;
2729 static int usb_device_del(const char *devname)
2734 if (strstart(devname, "host:", &p))
2735 return usb_host_device_close(p);
2737 if (!used_usb_ports)
2740 p = strchr(devname, '.');
2743 bus_num = strtoul(devname, NULL, 0);
2744 addr = strtoul(p + 1, NULL, 0);
2746 return usb_device_del_addr(bus_num, addr);
2749 void do_usb_add(const char *devname)
2751 usb_device_add(devname);
2754 void do_usb_del(const char *devname)
2756 usb_device_del(devname);
2763 const char *speed_str;
2766 term_printf("USB support not enabled\n");
2770 for (port = used_usb_ports; port; port = port->next) {
2774 switch(dev->speed) {
2778 case USB_SPEED_FULL:
2781 case USB_SPEED_HIGH:
2788 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
2789 0, dev->addr, speed_str, dev->devname);
2793 /***********************************************************/
2794 /* PCMCIA/Cardbus */
2796 static struct pcmcia_socket_entry_s {
2797 struct pcmcia_socket_s *socket;
2798 struct pcmcia_socket_entry_s *next;
2799 } *pcmcia_sockets = 0;
2801 void pcmcia_socket_register(struct pcmcia_socket_s *socket)
2803 struct pcmcia_socket_entry_s *entry;
2805 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2806 entry->socket = socket;
2807 entry->next = pcmcia_sockets;
2808 pcmcia_sockets = entry;
2811 void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
2813 struct pcmcia_socket_entry_s *entry, **ptr;
2815 ptr = &pcmcia_sockets;
2816 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2817 if (entry->socket == socket) {
2823 void pcmcia_info(void)
2825 struct pcmcia_socket_entry_s *iter;
2826 if (!pcmcia_sockets)
2827 term_printf("No PCMCIA sockets\n");
2829 for (iter = pcmcia_sockets; iter; iter = iter->next)
2830 term_printf("%s: %s\n", iter->socket->slot_string,
2831 iter->socket->attached ? iter->socket->card_string :
2835 /***********************************************************/
2836 /* register display */
2838 void register_displaystate(DisplayState *ds)
2848 DisplayState *get_displaystate(void)
2850 return display_state;
2855 static void dumb_display_init(void)
2857 DisplayState *ds = qemu_mallocz(sizeof(DisplayState));
2858 ds->surface = qemu_create_displaysurface(640, 480, 32, 640 * 4);
2859 register_displaystate(ds);
2862 /***********************************************************/
2865 #define MAX_IO_HANDLERS 64
2867 typedef struct IOHandlerRecord {
2869 IOCanRWHandler *fd_read_poll;
2871 IOHandler *fd_write;
2874 /* temporary data */
2876 struct IOHandlerRecord *next;
2879 static IOHandlerRecord *first_io_handler;
2881 /* XXX: fd_read_poll should be suppressed, but an API change is
2882 necessary in the character devices to suppress fd_can_read(). */
2883 int qemu_set_fd_handler2(int fd,
2884 IOCanRWHandler *fd_read_poll,
2886 IOHandler *fd_write,
2889 IOHandlerRecord **pioh, *ioh;
2891 if (!fd_read && !fd_write) {
2892 pioh = &first_io_handler;
2897 if (ioh->fd == fd) {
2904 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2908 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
2909 ioh->next = first_io_handler;
2910 first_io_handler = ioh;
2913 ioh->fd_read_poll = fd_read_poll;
2914 ioh->fd_read = fd_read;
2915 ioh->fd_write = fd_write;
2916 ioh->opaque = opaque;
2922 int qemu_set_fd_handler(int fd,
2924 IOHandler *fd_write,
2927 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
2931 /***********************************************************/
2932 /* Polling handling */
2934 typedef struct PollingEntry {
2937 struct PollingEntry *next;
2940 static PollingEntry *first_polling_entry;
2942 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
2944 PollingEntry **ppe, *pe;
2945 pe = qemu_mallocz(sizeof(PollingEntry));
2947 pe->opaque = opaque;
2948 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
2953 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
2955 PollingEntry **ppe, *pe;
2956 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
2958 if (pe->func == func && pe->opaque == opaque) {
2966 /***********************************************************/
2967 /* Wait objects support */
2968 typedef struct WaitObjects {
2970 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
2971 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
2972 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
2975 static WaitObjects wait_objects = {0};
2977 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2979 WaitObjects *w = &wait_objects;
2981 if (w->num >= MAXIMUM_WAIT_OBJECTS)
2983 w->events[w->num] = handle;
2984 w->func[w->num] = func;
2985 w->opaque[w->num] = opaque;
2990 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2993 WaitObjects *w = &wait_objects;
2996 for (i = 0; i < w->num; i++) {
2997 if (w->events[i] == handle)
3000 w->events[i] = w->events[i + 1];
3001 w->func[i] = w->func[i + 1];
3002 w->opaque[i] = w->opaque[i + 1];
3010 /***********************************************************/
3011 /* ram save/restore */
3013 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
3017 v = qemu_get_byte(f);
3020 if (qemu_get_buffer(f, buf, len) != len)
3024 v = qemu_get_byte(f);
3025 memset(buf, v, len);
3031 if (qemu_file_has_error(f))
3037 static int ram_load_v1(QEMUFile *f, void *opaque)
3042 if (qemu_get_be32(f) != phys_ram_size)
3044 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
3045 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
3052 #define BDRV_HASH_BLOCK_SIZE 1024
3053 #define IOBUF_SIZE 4096
3054 #define RAM_CBLOCK_MAGIC 0xfabe
3056 typedef struct RamDecompressState {
3059 uint8_t buf[IOBUF_SIZE];
3060 } RamDecompressState;
3062 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
3065 memset(s, 0, sizeof(*s));
3067 ret = inflateInit(&s->zstream);
3073 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
3077 s->zstream.avail_out = len;
3078 s->zstream.next_out = buf;
3079 while (s->zstream.avail_out > 0) {
3080 if (s->zstream.avail_in == 0) {
3081 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
3083 clen = qemu_get_be16(s->f);
3084 if (clen > IOBUF_SIZE)
3086 qemu_get_buffer(s->f, s->buf, clen);
3087 s->zstream.avail_in = clen;
3088 s->zstream.next_in = s->buf;
3090 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
3091 if (ret != Z_OK && ret != Z_STREAM_END) {
3098 static void ram_decompress_close(RamDecompressState *s)
3100 inflateEnd(&s->zstream);
3103 #define RAM_SAVE_FLAG_FULL 0x01
3104 #define RAM_SAVE_FLAG_COMPRESS 0x02
3105 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
3106 #define RAM_SAVE_FLAG_PAGE 0x08
3107 #define RAM_SAVE_FLAG_EOS 0x10
3109 static int is_dup_page(uint8_t *page, uint8_t ch)
3111 uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
3112 uint32_t *array = (uint32_t *)page;
3115 for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
3116 if (array[i] != val)
3123 static int ram_save_block(QEMUFile *f)
3125 static ram_addr_t current_addr = 0;
3126 ram_addr_t saved_addr = current_addr;
3127 ram_addr_t addr = 0;
3130 while (addr < phys_ram_size) {
3131 if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
3134 cpu_physical_memory_reset_dirty(current_addr,
3135 current_addr + TARGET_PAGE_SIZE,
3136 MIGRATION_DIRTY_FLAG);
3138 ch = *(phys_ram_base + current_addr);
3140 if (is_dup_page(phys_ram_base + current_addr, ch)) {
3141 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
3142 qemu_put_byte(f, ch);
3144 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
3145 qemu_put_buffer(f, phys_ram_base + current_addr, TARGET_PAGE_SIZE);
3151 addr += TARGET_PAGE_SIZE;
3152 current_addr = (saved_addr + addr) % phys_ram_size;
3158 static ram_addr_t ram_save_threshold = 10;
3160 static ram_addr_t ram_save_remaining(void)
3163 ram_addr_t count = 0;
3165 for (addr = 0; addr < phys_ram_size; addr += TARGET_PAGE_SIZE) {
3166 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3173 static int ram_save_live(QEMUFile *f, int stage, void *opaque)
3178 /* Make sure all dirty bits are set */
3179 for (addr = 0; addr < phys_ram_size; addr += TARGET_PAGE_SIZE) {
3180 if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3181 cpu_physical_memory_set_dirty(addr);
3184 /* Enable dirty memory tracking */
3185 cpu_physical_memory_set_dirty_tracking(1);
3187 qemu_put_be64(f, phys_ram_size | RAM_SAVE_FLAG_MEM_SIZE);
3190 while (!qemu_file_rate_limit(f)) {
3193 ret = ram_save_block(f);
3194 if (ret == 0) /* no more blocks */
3198 /* try transferring iterative blocks of memory */
3201 cpu_physical_memory_set_dirty_tracking(0);
3203 /* flush all remaining blocks regardless of rate limiting */
3204 while (ram_save_block(f) != 0);
3207 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
3209 return (stage == 2) && (ram_save_remaining() < ram_save_threshold);
3212 static int ram_load_dead(QEMUFile *f, void *opaque)
3214 RamDecompressState s1, *s = &s1;
3218 if (ram_decompress_open(s, f) < 0)
3220 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
3221 if (ram_decompress_buf(s, buf, 1) < 0) {
3222 fprintf(stderr, "Error while reading ram block header\n");
3226 if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
3227 fprintf(stderr, "Error while reading ram block address=0x%08" PRIx64, (uint64_t)i);
3232 printf("Error block header\n");
3236 ram_decompress_close(s);
3241 static int ram_load(QEMUFile *f, void *opaque, int version_id)
3246 if (version_id == 1)
3247 return ram_load_v1(f, opaque);
3249 if (version_id == 2) {
3250 if (qemu_get_be32(f) != phys_ram_size)
3252 return ram_load_dead(f, opaque);
3255 if (version_id != 3)
3259 addr = qemu_get_be64(f);
3261 flags = addr & ~TARGET_PAGE_MASK;
3262 addr &= TARGET_PAGE_MASK;
3264 if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
3265 if (addr != phys_ram_size)
3269 if (flags & RAM_SAVE_FLAG_FULL) {
3270 if (ram_load_dead(f, opaque) < 0)
3274 if (flags & RAM_SAVE_FLAG_COMPRESS) {
3275 uint8_t ch = qemu_get_byte(f);
3276 memset(phys_ram_base + addr, ch, TARGET_PAGE_SIZE);
3277 } else if (flags & RAM_SAVE_FLAG_PAGE)
3278 qemu_get_buffer(f, phys_ram_base + addr, TARGET_PAGE_SIZE);
3279 } while (!(flags & RAM_SAVE_FLAG_EOS));
3284 void qemu_service_io(void)
3286 CPUState *env = cpu_single_env;
3288 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
3290 if (env->kqemu_enabled) {
3291 kqemu_cpu_interrupt(env);
3297 /***********************************************************/
3298 /* bottom halves (can be seen as timers which expire ASAP) */
3309 static QEMUBH *first_bh = NULL;
3311 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
3314 bh = qemu_mallocz(sizeof(QEMUBH));
3316 bh->opaque = opaque;
3317 bh->next = first_bh;
3322 int qemu_bh_poll(void)
3328 for (bh = first_bh; bh; bh = bh->next) {
3329 if (!bh->deleted && bh->scheduled) {
3338 /* remove deleted bhs */
3352 void qemu_bh_schedule_idle(QEMUBH *bh)
3360 void qemu_bh_schedule(QEMUBH *bh)
3362 CPUState *env = cpu_single_env;
3367 /* stop the currently executing CPU to execute the BH ASAP */
3369 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
3373 void qemu_bh_cancel(QEMUBH *bh)
3378 void qemu_bh_delete(QEMUBH *bh)
3384 static void qemu_bh_update_timeout(int *timeout)
3388 for (bh = first_bh; bh; bh = bh->next) {
3389 if (!bh->deleted && bh->scheduled) {
3391 /* idle bottom halves will be polled at least
3393 *timeout = MIN(10, *timeout);
3395 /* non-idle bottom halves will be executed
3404 /***********************************************************/
3405 /* machine registration */
3407 static QEMUMachine *first_machine = NULL;
3409 int qemu_register_machine(QEMUMachine *m)
3412 pm = &first_machine;
3420 static QEMUMachine *find_machine(const char *name)
3424 for(m = first_machine; m != NULL; m = m->next) {
3425 if (!strcmp(m->name, name))
3431 /***********************************************************/
3432 /* main execution loop */
3434 static void gui_update(void *opaque)
3436 uint64_t interval = GUI_REFRESH_INTERVAL;
3437 DisplayState *ds = opaque;
3438 DisplayChangeListener *dcl = ds->listeners;
3442 while (dcl != NULL) {
3443 if (dcl->gui_timer_interval &&
3444 dcl->gui_timer_interval < interval)
3445 interval = dcl->gui_timer_interval;
3448 qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
3451 static void nographic_update(void *opaque)
3453 uint64_t interval = GUI_REFRESH_INTERVAL;
3455 qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
3458 struct vm_change_state_entry {
3459 VMChangeStateHandler *cb;
3461 LIST_ENTRY (vm_change_state_entry) entries;
3464 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3466 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3469 VMChangeStateEntry *e;
3471 e = qemu_mallocz(sizeof (*e));
3475 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3479 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3481 LIST_REMOVE (e, entries);
3485 static void vm_state_notify(int running, int reason)
3487 VMChangeStateEntry *e;
3489 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3490 e->cb(e->opaque, running, reason);
3499 vm_state_notify(1, 0);
3500 qemu_rearm_alarm_timer(alarm_timer);
3504 void vm_stop(int reason)
3507 cpu_disable_ticks();
3509 vm_state_notify(0, reason);
3513 /* reset/shutdown handler */
3515 typedef struct QEMUResetEntry {
3516 QEMUResetHandler *func;
3518 struct QEMUResetEntry *next;
3521 static QEMUResetEntry *first_reset_entry;
3522 static int reset_requested;
3523 static int shutdown_requested;
3524 static int powerdown_requested;
3526 int qemu_shutdown_requested(void)
3528 int r = shutdown_requested;
3529 shutdown_requested = 0;
3533 int qemu_reset_requested(void)
3535 int r = reset_requested;
3536 reset_requested = 0;
3540 int qemu_powerdown_requested(void)
3542 int r = powerdown_requested;
3543 powerdown_requested = 0;
3547 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
3549 QEMUResetEntry **pre, *re;
3551 pre = &first_reset_entry;
3552 while (*pre != NULL)
3553 pre = &(*pre)->next;
3554 re = qemu_mallocz(sizeof(QEMUResetEntry));
3556 re->opaque = opaque;
3561 void qemu_system_reset(void)
3565 /* reset all devices */
3566 for(re = first_reset_entry; re != NULL; re = re->next) {
3567 re->func(re->opaque);
3571 void qemu_system_reset_request(void)
3574 shutdown_requested = 1;
3576 reset_requested = 1;
3579 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
3582 void qemu_system_shutdown_request(void)
3584 shutdown_requested = 1;
3586 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
3589 void qemu_system_powerdown_request(void)
3591 powerdown_requested = 1;
3593 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
3597 static void host_main_loop_wait(int *timeout)
3603 /* XXX: need to suppress polling by better using win32 events */
3605 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
3606 ret |= pe->func(pe->opaque);
3610 WaitObjects *w = &wait_objects;
3612 ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
3613 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
3614 if (w->func[ret - WAIT_OBJECT_0])
3615 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
3617 /* Check for additional signaled events */
3618 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
3620 /* Check if event is signaled */
3621 ret2 = WaitForSingleObject(w->events[i], 0);
3622 if(ret2 == WAIT_OBJECT_0) {
3624 w->func[i](w->opaque[i]);
3625 } else if (ret2 == WAIT_TIMEOUT) {
3627 err = GetLastError();
3628 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
3631 } else if (ret == WAIT_TIMEOUT) {
3633 err = GetLastError();
3634 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
3641 static void host_main_loop_wait(int *timeout)
3646 void main_loop_wait(int timeout)
3648 IOHandlerRecord *ioh;
3649 fd_set rfds, wfds, xfds;
3653 qemu_bh_update_timeout(&timeout);
3655 host_main_loop_wait(&timeout);
3657 /* poll any events */
3658 /* XXX: separate device handlers from system ones */
3663 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3667 (!ioh->fd_read_poll ||
3668 ioh->fd_read_poll(ioh->opaque) != 0)) {
3669 FD_SET(ioh->fd, &rfds);
3673 if (ioh->fd_write) {
3674 FD_SET(ioh->fd, &wfds);
3680 tv.tv_sec = timeout / 1000;
3681 tv.tv_usec = (timeout % 1000) * 1000;
3683 #if defined(CONFIG_SLIRP)
3684 if (slirp_is_inited()) {
3685 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
3688 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
3690 IOHandlerRecord **pioh;
3692 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3693 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
3694 ioh->fd_read(ioh->opaque);
3696 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
3697 ioh->fd_write(ioh->opaque);
3701 /* remove deleted IO handlers */
3702 pioh = &first_io_handler;
3712 #if defined(CONFIG_SLIRP)
3713 if (slirp_is_inited()) {
3719 slirp_select_poll(&rfds, &wfds, &xfds);
3723 /* vm time timers */
3724 if (vm_running && likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))
3725 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
3726 qemu_get_clock(vm_clock));
3728 /* real time timers */
3729 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
3730 qemu_get_clock(rt_clock));
3732 /* Check bottom-halves last in case any of the earlier events triggered
3738 static int main_loop(void)
3741 #ifdef CONFIG_PROFILER
3746 cur_cpu = first_cpu;
3747 next_cpu = cur_cpu->next_cpu ?: first_cpu;
3754 #ifdef CONFIG_PROFILER
3755 ti = profile_getclock();
3760 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
3761 env->icount_decr.u16.low = 0;
3762 env->icount_extra = 0;
3763 count = qemu_next_deadline();
3764 count = (count + (1 << icount_time_shift) - 1)
3765 >> icount_time_shift;
3766 qemu_icount += count;
3767 decr = (count > 0xffff) ? 0xffff : count;
3769 env->icount_decr.u16.low = decr;
3770 env->icount_extra = count;
3772 ret = cpu_exec(env);
3773 #ifdef CONFIG_PROFILER
3774 qemu_time += profile_getclock() - ti;
3777 /* Fold pending instructions back into the
3778 instruction counter, and clear the interrupt flag. */
3779 qemu_icount -= (env->icount_decr.u16.low
3780 + env->icount_extra);
3781 env->icount_decr.u32 = 0;
3782 env->icount_extra = 0;
3784 next_cpu = env->next_cpu ?: first_cpu;
3785 if (event_pending && likely(ret != EXCP_DEBUG)) {
3786 ret = EXCP_INTERRUPT;
3790 if (ret == EXCP_HLT) {
3791 /* Give the next CPU a chance to run. */
3795 if (ret != EXCP_HALTED)
3797 /* all CPUs are halted ? */
3803 if (shutdown_requested) {
3804 ret = EXCP_INTERRUPT;
3812 if (reset_requested) {
3813 reset_requested = 0;
3814 qemu_system_reset();
3815 ret = EXCP_INTERRUPT;
3817 if (powerdown_requested) {
3818 powerdown_requested = 0;
3819 qemu_system_powerdown();
3820 ret = EXCP_INTERRUPT;
3822 if (unlikely(ret == EXCP_DEBUG)) {
3823 gdb_set_stop_cpu(cur_cpu);
3824 vm_stop(EXCP_DEBUG);
3826 /* If all cpus are halted then wait until the next IRQ */
3827 /* XXX: use timeout computed from timers */
3828 if (ret == EXCP_HALTED) {
3832 /* Advance virtual time to the next event. */
3833 if (use_icount == 1) {
3834 /* When not using an adaptive execution frequency
3835 we tend to get badly out of sync with real time,
3836 so just delay for a reasonable amount of time. */
3839 delta = cpu_get_icount() - cpu_get_clock();
3842 /* If virtual time is ahead of real time then just
3844 timeout = (delta / 1000000) + 1;
3846 /* Wait for either IO to occur or the next
3848 add = qemu_next_deadline();
3849 /* We advance the timer before checking for IO.
3850 Limit the amount we advance so that early IO
3851 activity won't get the guest too far ahead. */
3855 add = (add + (1 << icount_time_shift) - 1)
3856 >> icount_time_shift;
3858 timeout = delta / 1000000;
3869 if (shutdown_requested) {
3870 ret = EXCP_INTERRUPT;
3875 #ifdef CONFIG_PROFILER
3876 ti = profile_getclock();
3878 main_loop_wait(timeout);
3879 #ifdef CONFIG_PROFILER
3880 dev_time += profile_getclock() - ti;
3883 cpu_disable_ticks();
3887 static void help(int exitcode)
3889 /* Please keep in synch with QEMU_OPTION_ enums, qemu_options[]
3890 and qemu-doc.texi */
3891 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n"
3892 "usage: %s [options] [disk_image]\n"
3894 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
3896 "Standard options:\n"
3897 "-h or -help display this help and exit\n"
3898 "-M machine select emulated machine (-M ? for list)\n"
3899 "-cpu cpu select CPU (-cpu ? for list)\n"
3900 "-smp n set the number of CPUs to 'n' [default=1]\n"
3901 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
3902 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
3903 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
3904 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
3905 "-drive [file=file][,if=type][,bus=n][,unit=m][,media=d][,index=i]\n"
3906 " [,cyls=c,heads=h,secs=s[,trans=t]][,snapshot=on|off]\n"
3907 " [,cache=writethrough|writeback|none][,format=f][,serial=s]\n"
3908 " use 'file' as a drive image\n"
3909 "-mtdblock file use 'file' as on-board Flash memory image\n"
3910 "-sd file use 'file' as SecureDigital card image\n"
3911 "-pflash file use 'file' as a parallel flash image\n"
3912 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
3913 "-snapshot write to temporary files instead of disk image files\n"
3914 "-m megs set virtual RAM size to megs MB [default=%d]\n"
3916 "-k language use keyboard layout (for example \"fr\" for French)\n"
3919 "-audio-help print list of audio drivers and their options\n"
3920 "-soundhw c1,... enable audio support\n"
3921 " and only specified sound cards (comma separated list)\n"
3922 " use -soundhw ? to get the list of supported cards\n"
3923 " use -soundhw all to enable all of them\n"
3925 "-usb enable the USB driver (will be the default soon)\n"
3926 "-usbdevice name add the host or guest USB device 'name'\n"
3927 "-name string set the name of the guest\n"
3928 "-uuid %%08x-%%04x-%%04x-%%04x-%%012x\n"
3929 " specify machine UUID\n"
3931 "Display options:\n"
3932 "-nographic disable graphical output and redirect serial I/Os to console\n"
3933 #ifdef CONFIG_CURSES
3934 "-curses use a curses/ncurses interface instead of SDL\n"
3937 "-no-frame open SDL window without a frame and window decorations\n"
3938 "-alt-grab use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
3939 "-no-quit disable SDL window close capability\n"
3942 "-portrait rotate graphical output 90 deg left (only PXA LCD)\n"
3943 "-vga [std|cirrus|vmware|none]\n"
3944 " select video card type\n"
3945 "-full-screen start in full screen\n"
3946 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
3947 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
3949 "-vnc display start a VNC server on display\n"
3951 "Network options:\n"
3952 "-net nic[,vlan=n][,macaddr=addr][,model=type][,name=str]\n"
3953 " create a new Network Interface Card and connect it to VLAN 'n'\n"
3955 "-net user[,vlan=n][,name=str][,hostname=host]\n"
3956 " connect the user mode network stack to VLAN 'n' and send\n"
3957 " hostname 'host' to DHCP clients\n"
3960 "-net tap[,vlan=n][,name=str],ifname=name\n"
3961 " connect the host TAP network interface to VLAN 'n'\n"
3963 "-net tap[,vlan=n][,name=str][,fd=h][,ifname=name][,script=file][,downscript=dfile]\n"
3964 " connect the host TAP network interface to VLAN 'n' and use the\n"
3965 " network scripts 'file' (default=%s)\n"
3966 " and 'dfile' (default=%s);\n"
3967 " use '[down]script=no' to disable script execution;\n"
3968 " use 'fd=h' to connect to an already opened TAP interface\n"
3970 "-net socket[,vlan=n][,name=str][,fd=h][,listen=[host]:port][,connect=host:port]\n"
3971 " connect the vlan 'n' to another VLAN using a socket connection\n"
3972 "-net socket[,vlan=n][,name=str][,fd=h][,mcast=maddr:port]\n"
3973 " connect the vlan 'n' to multicast maddr and port\n"
3975 "-net vde[,vlan=n][,name=str][,sock=socketpath][,port=n][,group=groupname][,mode=octalmode]\n"
3976 " connect the vlan 'n' to port 'n' of a vde switch running\n"
3977 " on host and listening for incoming connections on 'socketpath'.\n"
3978 " Use group 'groupname' and mode 'octalmode' to change default\n"
3979 " ownership and permissions for communication port.\n"
3981 "-net none use it alone to have zero network devices; if no -net option\n"
3982 " is provided, the default is '-net nic -net user'\n"
3984 "-tftp dir allow tftp access to files in dir [-net user]\n"
3985 "-bootp file advertise file in BOOTP replies\n"
3987 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
3989 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
3990 " redirect TCP or UDP connections from host to guest [-net user]\n"
3993 "-bt hci,null dumb bluetooth HCI - doesn't respond to commands\n"
3994 "-bt hci,host[:id]\n"
3995 " use host's HCI with the given name\n"
3996 "-bt hci[,vlan=n]\n"
3997 " emulate a standard HCI in virtual scatternet 'n'\n"
3998 "-bt vhci[,vlan=n]\n"
3999 " add host computer to virtual scatternet 'n' using VHCI\n"
4000 "-bt device:dev[,vlan=n]\n"
4001 " emulate a bluetooth device 'dev' in scatternet 'n'\n"
4005 "i386 target only:\n"
4006 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
4007 "-rtc-td-hack use it to fix time drift in Windows ACPI HAL\n"
4008 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
4009 "-no-acpi disable ACPI\n"
4010 "-no-hpet disable HPET\n"
4012 "Linux boot specific:\n"
4013 "-kernel bzImage use 'bzImage' as kernel image\n"
4014 "-append cmdline use 'cmdline' as kernel command line\n"
4015 "-initrd file use 'file' as initial ram disk\n"
4017 "Debug/Expert options:\n"
4018 "-serial dev redirect the serial port to char device 'dev'\n"
4019 "-parallel dev redirect the parallel port to char device 'dev'\n"
4020 "-monitor dev redirect the monitor to char device 'dev'\n"
4021 "-pidfile file write PID to 'file'\n"
4022 "-S freeze CPU at startup (use 'c' to start execution)\n"
4023 "-s wait gdb connection to port\n"
4024 "-p port set gdb connection port [default=%s]\n"
4025 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
4026 "-hdachs c,h,s[,t]\n"
4027 " force hard disk 0 physical geometry and the optional BIOS\n"
4028 " translation (t=none or lba) (usually qemu can guess them)\n"
4029 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
4030 "-bios file set the filename for the BIOS\n"
4032 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
4033 "-no-kqemu disable KQEMU kernel module usage\n"
4036 "-enable-kvm enable KVM full virtualization support\n"
4038 "-no-reboot exit instead of rebooting\n"
4039 "-no-shutdown stop before shutdown\n"
4040 "-loadvm [tag|id]\n"
4041 " start right away with a saved state (loadvm in monitor)\n"
4043 "-daemonize daemonize QEMU after initializing\n"
4045 "-option-rom rom load a file, rom, into the option ROM space\n"
4046 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
4047 "-prom-env variable=value\n"
4048 " set OpenBIOS nvram variables\n"
4050 "-clock force the use of the given methods for timer alarm.\n"
4051 " To see what timers are available use -clock ?\n"
4052 "-localtime set the real time clock to local time [default=utc]\n"
4053 "-startdate select initial date of the clock\n"
4054 "-icount [N|auto]\n"
4055 " enable virtual instruction counter with 2^N clock ticks per instruction\n"
4056 "-echr chr set terminal escape character instead of ctrl-a\n"
4057 "-virtioconsole c\n"
4058 " set virtio console\n"
4059 "-show-cursor show cursor\n"
4060 #if defined(TARGET_ARM) || defined(TARGET_M68K)
4061 "-semihosting semihosting mode\n"
4063 #if defined(TARGET_ARM)
4064 "-old-param old param mode\n"
4066 "-tb-size n set TB size\n"
4067 "-incoming p prepare for incoming migration, listen on port p\n"
4069 "During emulation, the following keys are useful:\n"
4070 "ctrl-alt-f toggle full screen\n"
4071 "ctrl-alt-n switch to virtual console 'n'\n"
4072 "ctrl-alt toggle mouse and keyboard grab\n"
4074 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4079 DEFAULT_NETWORK_SCRIPT,
4080 DEFAULT_NETWORK_DOWN_SCRIPT,
4082 DEFAULT_GDBSTUB_PORT,
4087 #define HAS_ARG 0x0001
4090 /* Please keep in synch with help, qemu_options[] and
4092 /* Standard options: */
4105 QEMU_OPTION_mtdblock,
4109 QEMU_OPTION_snapshot,
4112 QEMU_OPTION_audio_help,
4113 QEMU_OPTION_soundhw,
4115 QEMU_OPTION_usbdevice,
4119 /* Display options: */
4120 QEMU_OPTION_nographic,
4122 QEMU_OPTION_no_frame,
4123 QEMU_OPTION_alt_grab,
4124 QEMU_OPTION_no_quit,
4126 QEMU_OPTION_portrait,
4128 QEMU_OPTION_full_screen,
4132 /* Network options: */
4140 /* i386 target only: */
4141 QEMU_OPTION_win2k_hack,
4142 QEMU_OPTION_rtc_td_hack,
4143 QEMU_OPTION_no_fd_bootchk,
4144 QEMU_OPTION_no_acpi,
4145 QEMU_OPTION_no_hpet,
4147 /* Linux boot specific: */
4152 /* Debug/Expert options: */
4154 QEMU_OPTION_parallel,
4155 QEMU_OPTION_monitor,
4156 QEMU_OPTION_pidfile,
4164 QEMU_OPTION_kernel_kqemu,
4165 QEMU_OPTION_no_kqemu,
4166 QEMU_OPTION_enable_kvm,
4167 QEMU_OPTION_no_reboot,
4168 QEMU_OPTION_no_shutdown,
4170 QEMU_OPTION_daemonize,
4171 QEMU_OPTION_option_rom,
4172 QEMU_OPTION_prom_env,
4174 QEMU_OPTION_localtime,
4175 QEMU_OPTION_startdate,
4178 QEMU_OPTION_virtiocon,
4179 QEMU_OPTION_show_cursor,
4180 QEMU_OPTION_semihosting,
4181 QEMU_OPTION_old_param,
4182 QEMU_OPTION_tb_size,
4183 QEMU_OPTION_incoming,
4186 typedef struct QEMUOption {
4192 static const QEMUOption qemu_options[] = {
4193 /* Please keep in synch with help, QEMU_OPTION_ enums, and
4195 /* Standard options: */
4196 { "h", 0, QEMU_OPTION_h },
4197 { "help", 0, QEMU_OPTION_h },
4198 { "M", HAS_ARG, QEMU_OPTION_M },
4199 { "cpu", HAS_ARG, QEMU_OPTION_cpu },
4200 { "smp", HAS_ARG, QEMU_OPTION_smp },
4201 { "fda", HAS_ARG, QEMU_OPTION_fda },
4202 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
4203 { "hda", HAS_ARG, QEMU_OPTION_hda },
4204 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
4205 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
4206 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
4207 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
4208 { "drive", HAS_ARG, QEMU_OPTION_drive },
4209 { "mtdblock", HAS_ARG, QEMU_OPTION_mtdblock },
4210 { "sd", HAS_ARG, QEMU_OPTION_sd },
4211 { "pflash", HAS_ARG, QEMU_OPTION_pflash },
4212 { "boot", HAS_ARG, QEMU_OPTION_boot },
4213 { "snapshot", 0, QEMU_OPTION_snapshot },
4214 { "m", HAS_ARG, QEMU_OPTION_m },
4216 { "k", HAS_ARG, QEMU_OPTION_k },
4219 { "audio-help", 0, QEMU_OPTION_audio_help },
4220 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
4222 { "usb", 0, QEMU_OPTION_usb },
4223 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
4224 { "name", HAS_ARG, QEMU_OPTION_name },
4225 { "uuid", HAS_ARG, QEMU_OPTION_uuid },
4227 /* Display options: */
4228 { "nographic", 0, QEMU_OPTION_nographic },
4229 #ifdef CONFIG_CURSES
4230 { "curses", 0, QEMU_OPTION_curses },
4233 { "no-frame", 0, QEMU_OPTION_no_frame },
4234 { "alt-grab", 0, QEMU_OPTION_alt_grab },
4235 { "no-quit", 0, QEMU_OPTION_no_quit },
4236 { "sdl", 0, QEMU_OPTION_sdl },
4238 { "portrait", 0, QEMU_OPTION_portrait },
4239 { "vga", HAS_ARG, QEMU_OPTION_vga },
4240 { "full-screen", 0, QEMU_OPTION_full_screen },
4241 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
4242 { "g", 1, QEMU_OPTION_g },
4244 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
4246 /* Network options: */
4247 { "net", HAS_ARG, QEMU_OPTION_net},
4249 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
4250 { "bootp", HAS_ARG, QEMU_OPTION_bootp },
4252 { "smb", HAS_ARG, QEMU_OPTION_smb },
4254 { "redir", HAS_ARG, QEMU_OPTION_redir },
4256 { "bt", HAS_ARG, QEMU_OPTION_bt },
4258 /* i386 target only: */
4259 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
4260 { "rtc-td-hack", 0, QEMU_OPTION_rtc_td_hack },
4261 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
4262 { "no-acpi", 0, QEMU_OPTION_no_acpi },
4263 { "no-hpet", 0, QEMU_OPTION_no_hpet },
4266 /* Linux boot specific: */
4267 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
4268 { "append", HAS_ARG, QEMU_OPTION_append },
4269 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
4271 /* Debug/Expert options: */
4272 { "serial", HAS_ARG, QEMU_OPTION_serial },
4273 { "parallel", HAS_ARG, QEMU_OPTION_parallel },
4274 { "monitor", HAS_ARG, QEMU_OPTION_monitor },
4275 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
4276 { "S", 0, QEMU_OPTION_S },
4277 { "s", 0, QEMU_OPTION_s },
4278 { "p", HAS_ARG, QEMU_OPTION_p },
4279 { "d", HAS_ARG, QEMU_OPTION_d },
4280 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
4281 { "L", HAS_ARG, QEMU_OPTION_L },
4282 { "bios", HAS_ARG, QEMU_OPTION_bios },
4284 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
4285 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
4288 { "enable-kvm", 0, QEMU_OPTION_enable_kvm },
4290 { "no-reboot", 0, QEMU_OPTION_no_reboot },
4291 { "no-shutdown", 0, QEMU_OPTION_no_shutdown },
4292 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
4293 { "daemonize", 0, QEMU_OPTION_daemonize },
4294 { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
4295 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
4296 { "prom-env", HAS_ARG, QEMU_OPTION_prom_env },
4298 { "clock", HAS_ARG, QEMU_OPTION_clock },
4299 { "localtime", 0, QEMU_OPTION_localtime },
4300 { "startdate", HAS_ARG, QEMU_OPTION_startdate },
4301 { "icount", HAS_ARG, QEMU_OPTION_icount },
4302 { "echr", HAS_ARG, QEMU_OPTION_echr },
4303 { "virtioconsole", HAS_ARG, QEMU_OPTION_virtiocon },
4304 { "show-cursor", 0, QEMU_OPTION_show_cursor },
4305 #if defined(TARGET_ARM) || defined(TARGET_M68K)
4306 { "semihosting", 0, QEMU_OPTION_semihosting },
4308 #if defined(TARGET_ARM)
4309 { "old-param", 0, QEMU_OPTION_old_param },
4311 { "tb-size", HAS_ARG, QEMU_OPTION_tb_size },
4312 { "incoming", HAS_ARG, QEMU_OPTION_incoming },
4316 /* password input */
4318 int qemu_key_check(BlockDriverState *bs, const char *name)
4323 if (!bdrv_is_encrypted(bs))
4326 term_printf("%s is encrypted.\n", name);
4327 for(i = 0; i < 3; i++) {
4328 monitor_readline("Password: ", 1, password, sizeof(password));
4329 if (bdrv_set_key(bs, password) == 0)
4331 term_printf("invalid password\n");
4336 static BlockDriverState *get_bdrv(int index)
4338 if (index > nb_drives)
4340 return drives_table[index].bdrv;
4343 static void read_passwords(void)
4345 BlockDriverState *bs;
4348 for(i = 0; i < 6; i++) {
4351 qemu_key_check(bs, bdrv_get_device_name(bs));
4356 struct soundhw soundhw[] = {
4357 #ifdef HAS_AUDIO_CHOICE
4358 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4364 { .init_isa = pcspk_audio_init }
4371 "Creative Sound Blaster 16",
4374 { .init_isa = SB16_init }
4378 #ifdef CONFIG_CS4231A
4384 { .init_isa = cs4231a_init }
4392 "Yamaha YMF262 (OPL3)",
4394 "Yamaha YM3812 (OPL2)",
4398 { .init_isa = Adlib_init }
4405 "Gravis Ultrasound GF1",
4408 { .init_isa = GUS_init }
4415 "Intel 82801AA AC97 Audio",
4418 { .init_pci = ac97_init }
4422 #ifdef CONFIG_ES1370
4425 "ENSONIQ AudioPCI ES1370",
4428 { .init_pci = es1370_init }
4432 #endif /* HAS_AUDIO_CHOICE */
4434 { NULL, NULL, 0, 0, { NULL } }
4437 static void select_soundhw (const char *optarg)
4441 if (*optarg == '?') {
4444 printf ("Valid sound card names (comma separated):\n");
4445 for (c = soundhw; c->name; ++c) {
4446 printf ("%-11s %s\n", c->name, c->descr);
4448 printf ("\n-soundhw all will enable all of the above\n");
4449 exit (*optarg != '?');
4457 if (!strcmp (optarg, "all")) {
4458 for (c = soundhw; c->name; ++c) {
4466 e = strchr (p, ',');
4467 l = !e ? strlen (p) : (size_t) (e - p);
4469 for (c = soundhw; c->name; ++c) {
4470 if (!strncmp (c->name, p, l)) {
4479 "Unknown sound card name (too big to show)\n");
4482 fprintf (stderr, "Unknown sound card name `%.*s'\n",
4487 p += l + (e != NULL);
4491 goto show_valid_cards;
4496 static void select_vgahw (const char *p)
4500 if (strstart(p, "std", &opts)) {
4501 std_vga_enabled = 1;
4502 cirrus_vga_enabled = 0;
4504 } else if (strstart(p, "cirrus", &opts)) {
4505 cirrus_vga_enabled = 1;
4506 std_vga_enabled = 0;
4508 } else if (strstart(p, "vmware", &opts)) {
4509 cirrus_vga_enabled = 0;
4510 std_vga_enabled = 0;
4512 } else if (strstart(p, "none", &opts)) {
4513 cirrus_vga_enabled = 0;
4514 std_vga_enabled = 0;
4518 fprintf(stderr, "Unknown vga type: %s\n", p);
4522 const char *nextopt;
4524 if (strstart(opts, ",retrace=", &nextopt)) {
4526 if (strstart(opts, "dumb", &nextopt))
4527 vga_retrace_method = VGA_RETRACE_DUMB;
4528 else if (strstart(opts, "precise", &nextopt))
4529 vga_retrace_method = VGA_RETRACE_PRECISE;
4530 else goto invalid_vga;
4531 } else goto invalid_vga;
4537 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
4539 exit(STATUS_CONTROL_C_EXIT);
4544 static int qemu_uuid_parse(const char *str, uint8_t *uuid)
4548 if(strlen(str) != 36)
4551 ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
4552 &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
4553 &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
4561 #define MAX_NET_CLIENTS 32
4565 static void termsig_handler(int signal)
4567 qemu_system_shutdown_request();
4570 static void termsig_setup(void)
4572 struct sigaction act;
4574 memset(&act, 0, sizeof(act));
4575 act.sa_handler = termsig_handler;
4576 sigaction(SIGINT, &act, NULL);
4577 sigaction(SIGHUP, &act, NULL);
4578 sigaction(SIGTERM, &act, NULL);
4583 int main(int argc, char **argv, char **envp)
4585 #ifdef CONFIG_GDBSTUB
4587 const char *gdbstub_port;
4589 uint32_t boot_devices_bitmap = 0;
4591 int snapshot, linux_boot, net_boot;
4592 const char *initrd_filename;
4593 const char *kernel_filename, *kernel_cmdline;
4594 const char *boot_devices = "";
4596 DisplayChangeListener *dcl;
4597 int cyls, heads, secs, translation;
4598 const char *net_clients[MAX_NET_CLIENTS];
4600 const char *bt_opts[MAX_BT_CMDLINE];
4604 const char *r, *optarg;
4605 CharDriverState *monitor_hd = NULL;
4606 const char *monitor_device;
4607 const char *serial_devices[MAX_SERIAL_PORTS];
4608 int serial_device_index;
4609 const char *parallel_devices[MAX_PARALLEL_PORTS];
4610 int parallel_device_index;
4611 const char *virtio_consoles[MAX_VIRTIO_CONSOLES];
4612 int virtio_console_index;
4613 const char *loadvm = NULL;
4614 QEMUMachine *machine;
4615 const char *cpu_model;
4616 const char *usb_devices[MAX_USB_CMDLINE];
4617 int usb_devices_index;
4620 const char *pid_file = NULL;
4622 const char *incoming = NULL;
4624 qemu_cache_utils_init(envp);
4626 LIST_INIT (&vm_change_state_head);
4629 struct sigaction act;
4630 sigfillset(&act.sa_mask);
4632 act.sa_handler = SIG_IGN;
4633 sigaction(SIGPIPE, &act, NULL);
4636 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
4637 /* Note: cpu_interrupt() is currently not SMP safe, so we force
4638 QEMU to run on a single CPU */
4643 h = GetCurrentProcess();
4644 if (GetProcessAffinityMask(h, &mask, &smask)) {
4645 for(i = 0; i < 32; i++) {
4646 if (mask & (1 << i))
4651 SetProcessAffinityMask(h, mask);
4657 register_machines();
4658 machine = first_machine;
4660 initrd_filename = NULL;
4662 vga_ram_size = VGA_RAM_SIZE;
4663 #ifdef CONFIG_GDBSTUB
4665 gdbstub_port = DEFAULT_GDBSTUB_PORT;
4670 kernel_filename = NULL;
4671 kernel_cmdline = "";
4672 cyls = heads = secs = 0;
4673 translation = BIOS_ATA_TRANSLATION_AUTO;
4674 monitor_device = "vc";
4676 serial_devices[0] = "vc:80Cx24C";
4677 for(i = 1; i < MAX_SERIAL_PORTS; i++)
4678 serial_devices[i] = NULL;
4679 serial_device_index = 0;
4681 parallel_devices[0] = "vc:640x480";
4682 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
4683 parallel_devices[i] = NULL;
4684 parallel_device_index = 0;
4686 virtio_consoles[0] = "vc:80Cx24C";
4687 for(i = 1; i < MAX_VIRTIO_CONSOLES; i++)
4688 virtio_consoles[i] = NULL;
4689 virtio_console_index = 0;
4691 usb_devices_index = 0;
4710 hda_index = drive_add(argv[optind++], HD_ALIAS, 0);
4712 const QEMUOption *popt;
4715 /* Treat --foo the same as -foo. */
4718 popt = qemu_options;
4721 fprintf(stderr, "%s: invalid option -- '%s'\n",
4725 if (!strcmp(popt->name, r + 1))
4729 if (popt->flags & HAS_ARG) {
4730 if (optind >= argc) {
4731 fprintf(stderr, "%s: option '%s' requires an argument\n",
4735 optarg = argv[optind++];
4740 switch(popt->index) {
4742 machine = find_machine(optarg);
4745 printf("Supported machines are:\n");
4746 for(m = first_machine; m != NULL; m = m->next) {
4747 printf("%-10s %s%s\n",
4749 m == first_machine ? " (default)" : "");
4751 exit(*optarg != '?');
4754 case QEMU_OPTION_cpu:
4755 /* hw initialization will check this */
4756 if (*optarg == '?') {
4757 /* XXX: implement xxx_cpu_list for targets that still miss it */
4758 #if defined(cpu_list)
4759 cpu_list(stdout, &fprintf);
4766 case QEMU_OPTION_initrd:
4767 initrd_filename = optarg;
4769 case QEMU_OPTION_hda:
4771 hda_index = drive_add(optarg, HD_ALIAS, 0);
4773 hda_index = drive_add(optarg, HD_ALIAS
4774 ",cyls=%d,heads=%d,secs=%d%s",
4775 0, cyls, heads, secs,
4776 translation == BIOS_ATA_TRANSLATION_LBA ?
4778 translation == BIOS_ATA_TRANSLATION_NONE ?
4779 ",trans=none" : "");
4781 case QEMU_OPTION_hdb:
4782 case QEMU_OPTION_hdc:
4783 case QEMU_OPTION_hdd:
4784 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
4786 case QEMU_OPTION_drive:
4787 drive_add(NULL, "%s", optarg);
4789 case QEMU_OPTION_mtdblock:
4790 drive_add(optarg, MTD_ALIAS);
4792 case QEMU_OPTION_sd:
4793 drive_add(optarg, SD_ALIAS);
4795 case QEMU_OPTION_pflash:
4796 drive_add(optarg, PFLASH_ALIAS);
4798 case QEMU_OPTION_snapshot:
4801 case QEMU_OPTION_hdachs:
4805 cyls = strtol(p, (char **)&p, 0);
4806 if (cyls < 1 || cyls > 16383)
4811 heads = strtol(p, (char **)&p, 0);
4812 if (heads < 1 || heads > 16)
4817 secs = strtol(p, (char **)&p, 0);
4818 if (secs < 1 || secs > 63)
4822 if (!strcmp(p, "none"))
4823 translation = BIOS_ATA_TRANSLATION_NONE;
4824 else if (!strcmp(p, "lba"))
4825 translation = BIOS_ATA_TRANSLATION_LBA;
4826 else if (!strcmp(p, "auto"))
4827 translation = BIOS_ATA_TRANSLATION_AUTO;
4830 } else if (*p != '\0') {
4832 fprintf(stderr, "qemu: invalid physical CHS format\n");
4835 if (hda_index != -1)
4836 snprintf(drives_opt[hda_index].opt,
4837 sizeof(drives_opt[hda_index].opt),
4838 HD_ALIAS ",cyls=%d,heads=%d,secs=%d%s",
4839 0, cyls, heads, secs,
4840 translation == BIOS_ATA_TRANSLATION_LBA ?
4842 translation == BIOS_ATA_TRANSLATION_NONE ?
4843 ",trans=none" : "");
4846 case QEMU_OPTION_nographic:
4849 #ifdef CONFIG_CURSES
4850 case QEMU_OPTION_curses:
4854 case QEMU_OPTION_portrait:
4857 case QEMU_OPTION_kernel:
4858 kernel_filename = optarg;
4860 case QEMU_OPTION_append:
4861 kernel_cmdline = optarg;
4863 case QEMU_OPTION_cdrom:
4864 drive_add(optarg, CDROM_ALIAS);
4866 case QEMU_OPTION_boot:
4867 boot_devices = optarg;
4868 /* We just do some generic consistency checks */
4870 /* Could easily be extended to 64 devices if needed */
4873 boot_devices_bitmap = 0;
4874 for (p = boot_devices; *p != '\0'; p++) {
4875 /* Allowed boot devices are:
4876 * a b : floppy disk drives
4877 * c ... f : IDE disk drives
4878 * g ... m : machine implementation dependant drives
4879 * n ... p : network devices
4880 * It's up to each machine implementation to check
4881 * if the given boot devices match the actual hardware
4882 * implementation and firmware features.
4884 if (*p < 'a' || *p > 'q') {
4885 fprintf(stderr, "Invalid boot device '%c'\n", *p);
4888 if (boot_devices_bitmap & (1 << (*p - 'a'))) {
4890 "Boot device '%c' was given twice\n",*p);
4893 boot_devices_bitmap |= 1 << (*p - 'a');
4897 case QEMU_OPTION_fda:
4898 case QEMU_OPTION_fdb:
4899 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
4902 case QEMU_OPTION_no_fd_bootchk:
4906 case QEMU_OPTION_net:
4907 if (nb_net_clients >= MAX_NET_CLIENTS) {
4908 fprintf(stderr, "qemu: too many network clients\n");
4911 net_clients[nb_net_clients] = optarg;
4915 case QEMU_OPTION_tftp:
4916 tftp_prefix = optarg;
4918 case QEMU_OPTION_bootp:
4919 bootp_filename = optarg;
4922 case QEMU_OPTION_smb:
4923 net_slirp_smb(optarg);
4926 case QEMU_OPTION_redir:
4927 net_slirp_redir(optarg);
4930 case QEMU_OPTION_bt:
4931 if (nb_bt_opts >= MAX_BT_CMDLINE) {
4932 fprintf(stderr, "qemu: too many bluetooth options\n");
4935 bt_opts[nb_bt_opts++] = optarg;
4938 case QEMU_OPTION_audio_help:
4942 case QEMU_OPTION_soundhw:
4943 select_soundhw (optarg);
4949 case QEMU_OPTION_m: {
4953 value = strtoul(optarg, &ptr, 10);
4955 case 0: case 'M': case 'm':
4962 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
4966 /* On 32-bit hosts, QEMU is limited by virtual address space */
4967 if (value > (2047 << 20)
4969 && HOST_LONG_BITS == 32
4972 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
4975 if (value != (uint64_t)(ram_addr_t)value) {
4976 fprintf(stderr, "qemu: ram size too large\n");
4985 const CPULogItem *item;
4987 mask = cpu_str_to_log_mask(optarg);
4989 printf("Log items (comma separated):\n");
4990 for(item = cpu_log_items; item->mask != 0; item++) {
4991 printf("%-10s %s\n", item->name, item->help);
4998 #ifdef CONFIG_GDBSTUB
5003 gdbstub_port = optarg;
5009 case QEMU_OPTION_bios:
5016 keyboard_layout = optarg;
5018 case QEMU_OPTION_localtime:
5021 case QEMU_OPTION_vga:
5022 select_vgahw (optarg);
5029 w = strtol(p, (char **)&p, 10);
5032 fprintf(stderr, "qemu: invalid resolution or depth\n");
5038 h = strtol(p, (char **)&p, 10);
5043 depth = strtol(p, (char **)&p, 10);
5044 if (depth != 8 && depth != 15 && depth != 16 &&
5045 depth != 24 && depth != 32)
5047 } else if (*p == '\0') {
5048 depth = graphic_depth;
5055 graphic_depth = depth;
5058 case QEMU_OPTION_echr:
5061 term_escape_char = strtol(optarg, &r, 0);
5063 printf("Bad argument to echr\n");
5066 case QEMU_OPTION_monitor:
5067 monitor_device = optarg;
5069 case QEMU_OPTION_serial:
5070 if (serial_device_index >= MAX_SERIAL_PORTS) {
5071 fprintf(stderr, "qemu: too many serial ports\n");
5074 serial_devices[serial_device_index] = optarg;
5075 serial_device_index++;
5077 case QEMU_OPTION_virtiocon:
5078 if (virtio_console_index >= MAX_VIRTIO_CONSOLES) {
5079 fprintf(stderr, "qemu: too many virtio consoles\n");
5082 virtio_consoles[virtio_console_index] = optarg;
5083 virtio_console_index++;
5085 case QEMU_OPTION_parallel:
5086 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
5087 fprintf(stderr, "qemu: too many parallel ports\n");
5090 parallel_devices[parallel_device_index] = optarg;
5091 parallel_device_index++;
5093 case QEMU_OPTION_loadvm:
5096 case QEMU_OPTION_full_screen:
5100 case QEMU_OPTION_no_frame:
5103 case QEMU_OPTION_alt_grab:
5106 case QEMU_OPTION_no_quit:
5109 case QEMU_OPTION_sdl:
5113 case QEMU_OPTION_pidfile:
5117 case QEMU_OPTION_win2k_hack:
5118 win2k_install_hack = 1;
5120 case QEMU_OPTION_rtc_td_hack:
5125 case QEMU_OPTION_no_kqemu:
5128 case QEMU_OPTION_kernel_kqemu:
5133 case QEMU_OPTION_enable_kvm:
5140 case QEMU_OPTION_usb:
5143 case QEMU_OPTION_usbdevice:
5145 if (usb_devices_index >= MAX_USB_CMDLINE) {
5146 fprintf(stderr, "Too many USB devices\n");
5149 usb_devices[usb_devices_index] = optarg;
5150 usb_devices_index++;
5152 case QEMU_OPTION_smp:
5153 smp_cpus = atoi(optarg);
5155 fprintf(stderr, "Invalid number of CPUs\n");
5159 case QEMU_OPTION_vnc:
5160 vnc_display = optarg;
5162 case QEMU_OPTION_no_acpi:
5165 case QEMU_OPTION_no_hpet:
5168 case QEMU_OPTION_no_reboot:
5171 case QEMU_OPTION_no_shutdown:
5174 case QEMU_OPTION_show_cursor:
5177 case QEMU_OPTION_uuid:
5178 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
5179 fprintf(stderr, "Fail to parse UUID string."
5180 " Wrong format.\n");
5184 case QEMU_OPTION_daemonize:
5187 case QEMU_OPTION_option_rom:
5188 if (nb_option_roms >= MAX_OPTION_ROMS) {
5189 fprintf(stderr, "Too many option ROMs\n");
5192 option_rom[nb_option_roms] = optarg;
5195 case QEMU_OPTION_semihosting:
5196 semihosting_enabled = 1;
5198 case QEMU_OPTION_name:
5201 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
5202 case QEMU_OPTION_prom_env:
5203 if (nb_prom_envs >= MAX_PROM_ENVS) {
5204 fprintf(stderr, "Too many prom variables\n");
5207 prom_envs[nb_prom_envs] = optarg;
5212 case QEMU_OPTION_old_param:
5216 case QEMU_OPTION_clock:
5217 configure_alarms(optarg);
5219 case QEMU_OPTION_startdate:
5222 time_t rtc_start_date;
5223 if (!strcmp(optarg, "now")) {
5224 rtc_date_offset = -1;
5226 if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
5234 } else if (sscanf(optarg, "%d-%d-%d",
5237 &tm.tm_mday) == 3) {
5246 rtc_start_date = mktimegm(&tm);
5247 if (rtc_start_date == -1) {
5249 fprintf(stderr, "Invalid date format. Valid format are:\n"
5250 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
5253 rtc_date_offset = time(NULL) - rtc_start_date;
5257 case QEMU_OPTION_tb_size:
5258 tb_size = strtol(optarg, NULL, 0);
5262 case QEMU_OPTION_icount:
5264 if (strcmp(optarg, "auto") == 0) {
5265 icount_time_shift = -1;
5267 icount_time_shift = strtol(optarg, NULL, 0);
5270 case QEMU_OPTION_incoming:
5277 #if defined(CONFIG_KVM) && defined(USE_KQEMU)
5278 if (kvm_allowed && kqemu_allowed) {
5280 "You can not enable both KVM and kqemu at the same time\n");
5285 machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
5286 if (smp_cpus > machine->max_cpus) {
5287 fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
5288 "supported by machine `%s' (%d)\n", smp_cpus, machine->name,
5294 if (serial_device_index == 0)
5295 serial_devices[0] = "stdio";
5296 if (parallel_device_index == 0)
5297 parallel_devices[0] = "null";
5298 if (strncmp(monitor_device, "vc", 2) == 0)
5299 monitor_device = "stdio";
5300 if (virtio_console_index == 0)
5301 virtio_consoles[0] = "null";
5308 if (pipe(fds) == -1)
5319 len = read(fds[0], &status, 1);
5320 if (len == -1 && (errno == EINTR))
5325 else if (status == 1) {
5326 fprintf(stderr, "Could not acquire pidfile\n");
5343 signal(SIGTSTP, SIG_IGN);
5344 signal(SIGTTOU, SIG_IGN);
5345 signal(SIGTTIN, SIG_IGN);
5349 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
5352 write(fds[1], &status, 1);
5354 fprintf(stderr, "Could not acquire pid file\n");
5362 linux_boot = (kernel_filename != NULL);
5363 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
5365 if (!linux_boot && net_boot == 0 &&
5366 !machine->nodisk_ok && nb_drives_opt == 0)
5369 if (!linux_boot && *kernel_cmdline != '\0') {
5370 fprintf(stderr, "-append only allowed with -kernel option\n");
5374 if (!linux_boot && initrd_filename != NULL) {
5375 fprintf(stderr, "-initrd only allowed with -kernel option\n");
5379 /* boot to floppy or the default cd if no hard disk defined yet */
5380 if (!boot_devices[0]) {
5381 boot_devices = "cad";
5383 setvbuf(stdout, NULL, _IOLBF, 0);
5386 if (init_timer_alarm() < 0) {
5387 fprintf(stderr, "could not initialize alarm timer\n");
5390 if (use_icount && icount_time_shift < 0) {
5392 /* 125MIPS seems a reasonable initial guess at the guest speed.
5393 It will be corrected fairly quickly anyway. */
5394 icount_time_shift = 3;
5395 init_icount_adjust();
5402 /* init network clients */
5403 if (nb_net_clients == 0) {
5404 /* if no clients, we use a default config */
5405 net_clients[nb_net_clients++] = "nic";
5407 net_clients[nb_net_clients++] = "user";
5411 for(i = 0;i < nb_net_clients; i++) {
5412 if (net_client_parse(net_clients[i]) < 0)
5418 /* XXX: this should be moved in the PC machine instantiation code */
5419 if (net_boot != 0) {
5421 for (i = 0; i < nb_nics && i < 4; i++) {
5422 const char *model = nd_table[i].model;
5424 if (net_boot & (1 << i)) {
5427 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
5428 if (get_image_size(buf) > 0) {
5429 if (nb_option_roms >= MAX_OPTION_ROMS) {
5430 fprintf(stderr, "Too many option ROMs\n");
5433 option_rom[nb_option_roms] = strdup(buf);
5440 fprintf(stderr, "No valid PXE rom found for network device\n");
5446 /* init the bluetooth world */
5447 for (i = 0; i < nb_bt_opts; i++)
5448 if (bt_parse(bt_opts[i]))
5451 /* init the memory */
5452 phys_ram_size = machine->ram_require & ~RAMSIZE_FIXED;
5454 if (machine->ram_require & RAMSIZE_FIXED) {
5456 if (ram_size < phys_ram_size) {
5457 fprintf(stderr, "Machine `%s' requires %llu bytes of memory\n",
5458 machine->name, (unsigned long long) phys_ram_size);
5462 phys_ram_size = ram_size;
5464 ram_size = phys_ram_size;
5467 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5469 phys_ram_size += ram_size;
5472 phys_ram_base = qemu_vmalloc(phys_ram_size);
5473 if (!phys_ram_base) {
5474 fprintf(stderr, "Could not allocate physical memory\n");
5478 /* init the dynamic translator */
5479 cpu_exec_init_all(tb_size * 1024 * 1024);
5483 /* we always create the cdrom drive, even if no disk is there */
5485 if (nb_drives_opt < MAX_DRIVES)
5486 drive_add(NULL, CDROM_ALIAS);
5488 /* we always create at least one floppy */
5490 if (nb_drives_opt < MAX_DRIVES)
5491 drive_add(NULL, FD_ALIAS, 0);
5493 /* we always create one sd slot, even if no card is in it */
5495 if (nb_drives_opt < MAX_DRIVES)
5496 drive_add(NULL, SD_ALIAS);
5498 /* open the virtual block devices */
5500 for(i = 0; i < nb_drives_opt; i++)
5501 if (drive_init(&drives_opt[i], snapshot, machine) == -1)
5504 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
5505 register_savevm_live("ram", 0, 3, ram_save_live, NULL, ram_load, NULL);
5508 /* must be after terminal init, SDL library changes signal handlers */
5512 /* Maintain compatibility with multiple stdio monitors */
5513 if (!strcmp(monitor_device,"stdio")) {
5514 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
5515 const char *devname = serial_devices[i];
5516 if (devname && !strcmp(devname,"mon:stdio")) {
5517 monitor_device = NULL;
5519 } else if (devname && !strcmp(devname,"stdio")) {
5520 monitor_device = NULL;
5521 serial_devices[i] = "mon:stdio";
5527 if (kvm_enabled()) {
5530 ret = kvm_init(smp_cpus);
5532 fprintf(stderr, "failed to initialize KVM\n");
5537 if (monitor_device) {
5538 monitor_hd = qemu_chr_open("monitor", monitor_device, NULL);
5540 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
5545 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5546 const char *devname = serial_devices[i];
5547 if (devname && strcmp(devname, "none")) {
5549 snprintf(label, sizeof(label), "serial%d", i);
5550 serial_hds[i] = qemu_chr_open(label, devname, NULL);
5551 if (!serial_hds[i]) {
5552 fprintf(stderr, "qemu: could not open serial device '%s'\n",
5559 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5560 const char *devname = parallel_devices[i];
5561 if (devname && strcmp(devname, "none")) {
5563 snprintf(label, sizeof(label), "parallel%d", i);
5564 parallel_hds[i] = qemu_chr_open(label, devname, NULL);
5565 if (!parallel_hds[i]) {
5566 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
5573 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
5574 const char *devname = virtio_consoles[i];
5575 if (devname && strcmp(devname, "none")) {
5577 snprintf(label, sizeof(label), "virtcon%d", i);
5578 virtcon_hds[i] = qemu_chr_open(label, devname, NULL);
5579 if (!virtcon_hds[i]) {
5580 fprintf(stderr, "qemu: could not open virtio console '%s'\n",
5587 machine->init(ram_size, vga_ram_size, boot_devices,
5588 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
5590 /* Set KVM's vcpu state to qemu's initial CPUState. */
5591 if (kvm_enabled()) {
5594 ret = kvm_sync_vcpus();
5596 fprintf(stderr, "failed to initialize vcpus\n");
5601 /* init USB devices */
5603 for(i = 0; i < usb_devices_index; i++) {
5604 if (usb_device_add(usb_devices[i]) < 0) {
5605 fprintf(stderr, "Warning: could not add USB device %s\n",
5612 dumb_display_init();
5613 /* just use the first displaystate for the moment */
5618 fprintf(stderr, "fatal: -nographic can't be used with -curses\n");
5622 #if defined(CONFIG_CURSES)
5624 /* At the moment curses cannot be used with other displays */
5625 curses_display_init(ds, full_screen);
5629 if (vnc_display != NULL) {
5630 vnc_display_init(ds);
5631 if (vnc_display_open(ds, vnc_display) < 0)
5634 #if defined(CONFIG_SDL)
5635 if (sdl || !vnc_display)
5636 sdl_display_init(ds, full_screen, no_frame);
5637 #elif defined(CONFIG_COCOA)
5638 if (sdl || !vnc_display)
5639 cocoa_display_init(ds, full_screen);
5645 dcl = ds->listeners;
5646 while (dcl != NULL) {
5647 if (dcl->dpy_refresh != NULL) {
5648 ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
5649 qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
5654 if (nographic || (vnc_display && !sdl)) {
5655 nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
5656 qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
5659 text_consoles_set_display(display_state);
5661 if (monitor_device && monitor_hd)
5662 monitor_init(monitor_hd, !nographic);
5664 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5665 const char *devname = serial_devices[i];
5666 if (devname && strcmp(devname, "none")) {
5668 snprintf(label, sizeof(label), "serial%d", i);
5669 if (strstart(devname, "vc", 0))
5670 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
5674 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5675 const char *devname = parallel_devices[i];
5676 if (devname && strcmp(devname, "none")) {
5678 snprintf(label, sizeof(label), "parallel%d", i);
5679 if (strstart(devname, "vc", 0))
5680 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
5684 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
5685 const char *devname = virtio_consoles[i];
5686 if (virtcon_hds[i] && devname) {
5688 snprintf(label, sizeof(label), "virtcon%d", i);
5689 if (strstart(devname, "vc", 0))
5690 qemu_chr_printf(virtcon_hds[i], "virtio console%d\r\n", i);
5694 #ifdef CONFIG_GDBSTUB
5696 /* XXX: use standard host:port notation and modify options
5698 if (gdbserver_start(gdbstub_port) < 0) {
5699 fprintf(stderr, "qemu: could not open gdbstub device on port '%s'\n",
5710 autostart = 0; /* fixme how to deal with -daemonize */
5711 qemu_start_incoming_migration(incoming);
5715 /* XXX: simplify init */
5728 len = write(fds[1], &status, 1);
5729 if (len == -1 && (errno == EINTR))
5736 TFR(fd = open("/dev/null", O_RDWR));