4 * Copyright (c) 2003-2008 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25 #include "hw/boards.h"
27 #include "hw/pcmcia.h"
29 #include "hw/audiodev.h"
37 #include "qemu-timer.h"
38 #include "qemu-char.h"
40 #include "audio/audio.h"
41 #include "migration.h"
53 #include <sys/times.h>
57 #include <sys/ioctl.h>
58 #include <sys/resource.h>
59 #include <sys/socket.h>
60 #include <netinet/in.h>
62 #if defined(__NetBSD__)
63 #include <net/if_tap.h>
66 #include <linux/if_tun.h>
68 #include <arpa/inet.h>
71 #include <sys/select.h>
79 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
80 #include <freebsd/stdlib.h>
85 #include <linux/rtc.h>
87 /* For the benefit of older linux systems which don't supply it,
88 we use a local copy of hpet.h. */
89 /* #include <linux/hpet.h> */
92 #include <linux/ppdev.h>
93 #include <linux/parport.h>
97 #include <sys/ethernet.h>
98 #include <sys/sockio.h>
99 #include <netinet/arp.h>
100 #include <netinet/in.h>
101 #include <netinet/in_systm.h>
102 #include <netinet/ip.h>
103 #include <netinet/ip_icmp.h> // must come after ip.h
104 #include <netinet/udp.h>
105 #include <netinet/tcp.h>
113 #include "qemu_socket.h"
115 #if defined(CONFIG_SLIRP)
116 #include "libslirp.h"
119 #if defined(__OpenBSD__)
123 #if defined(CONFIG_VDE)
124 #include <libvdeplug.h>
129 #include <sys/timeb.h>
130 #include <mmsystem.h>
131 #define getopt_long_only getopt_long
132 #define memalign(align, size) malloc(size)
139 #endif /* CONFIG_SDL */
143 #define main qemu_main
144 #endif /* CONFIG_COCOA */
148 #include "exec-all.h"
150 #define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
151 #define DEFAULT_NETWORK_DOWN_SCRIPT "/etc/qemu-ifdown"
153 #define SMBD_COMMAND "/usr/sfw/sbin/smbd"
155 #define SMBD_COMMAND "/usr/sbin/smbd"
158 //#define DEBUG_UNUSED_IOPORT
159 //#define DEBUG_IOPORT
161 //#define DEBUG_SLIRP
164 #define DEFAULT_RAM_SIZE 144
166 #define DEFAULT_RAM_SIZE 128
169 /* Max number of USB devices that can be specified on the commandline. */
170 #define MAX_USB_CMDLINE 8
172 /* Max number of bluetooth switches on the commandline. */
173 #define MAX_BT_CMDLINE 10
175 /* XXX: use a two level table to limit memory usage */
176 #define MAX_IOPORTS 65536
178 const char *bios_dir = CONFIG_QEMU_SHAREDIR;
179 const char *bios_name = NULL;
180 static void *ioport_opaque[MAX_IOPORTS];
181 static IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
182 static IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
183 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
184 to store the VM snapshots */
185 DriveInfo drives_table[MAX_DRIVES+1];
187 /* point to the block driver where the snapshots are managed */
188 static BlockDriverState *bs_snapshots;
189 static int vga_ram_size;
190 enum vga_retrace_method vga_retrace_method = VGA_RETRACE_DUMB;
191 DisplayState display_state;
194 const char* keyboard_layout = NULL;
195 int64_t ticks_per_sec;
198 NICInfo nd_table[MAX_NICS];
200 static int rtc_utc = 1;
201 static int rtc_date_offset = -1; /* -1 means no change */
202 int cirrus_vga_enabled = 1;
203 int vmsvga_enabled = 0;
205 int graphic_width = 1024;
206 int graphic_height = 768;
207 int graphic_depth = 8;
209 int graphic_width = 800;
210 int graphic_height = 600;
211 int graphic_depth = 15;
213 static int full_screen = 0;
214 static int no_frame = 0;
216 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
217 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
219 int win2k_install_hack = 0;
223 const char *vnc_display;
224 int acpi_enabled = 1;
229 int graphic_rotate = 0;
231 const char *option_rom[MAX_OPTION_ROMS];
233 int semihosting_enabled = 0;
237 const char *qemu_name;
240 unsigned int nb_prom_envs = 0;
241 const char *prom_envs[MAX_PROM_ENVS];
243 static int nb_drives_opt;
244 static struct drive_opt {
247 } drives_opt[MAX_DRIVES];
249 static CPUState *cur_cpu;
250 static CPUState *next_cpu;
251 static int event_pending = 1;
252 /* Conversion factor from emulated instructions to virtual clock ticks. */
253 static int icount_time_shift;
254 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
255 #define MAX_ICOUNT_SHIFT 10
256 /* Compensate for varying guest execution speed. */
257 static int64_t qemu_icount_bias;
258 static QEMUTimer *icount_rt_timer;
259 static QEMUTimer *icount_vm_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;
410 /***********************************************************/
412 void cpu_outb(CPUState *env, int addr, int val)
415 if (loglevel & CPU_LOG_IOPORT)
416 fprintf(logfile, "outb: %04x %02x\n", addr, val);
418 ioport_write(0, addr, val);
421 env->last_io_time = cpu_get_time_fast();
425 void cpu_outw(CPUState *env, int addr, int val)
428 if (loglevel & CPU_LOG_IOPORT)
429 fprintf(logfile, "outw: %04x %04x\n", addr, val);
431 ioport_write(1, addr, val);
434 env->last_io_time = cpu_get_time_fast();
438 void cpu_outl(CPUState *env, int addr, int val)
441 if (loglevel & CPU_LOG_IOPORT)
442 fprintf(logfile, "outl: %04x %08x\n", addr, val);
444 ioport_write(2, addr, val);
447 env->last_io_time = cpu_get_time_fast();
451 int cpu_inb(CPUState *env, int addr)
454 val = ioport_read(0, addr);
456 if (loglevel & CPU_LOG_IOPORT)
457 fprintf(logfile, "inb : %04x %02x\n", addr, val);
461 env->last_io_time = cpu_get_time_fast();
466 int cpu_inw(CPUState *env, int addr)
469 val = ioport_read(1, addr);
471 if (loglevel & CPU_LOG_IOPORT)
472 fprintf(logfile, "inw : %04x %04x\n", addr, val);
476 env->last_io_time = cpu_get_time_fast();
481 int cpu_inl(CPUState *env, int addr)
484 val = ioport_read(2, addr);
486 if (loglevel & CPU_LOG_IOPORT)
487 fprintf(logfile, "inl : %04x %08x\n", addr, val);
491 env->last_io_time = cpu_get_time_fast();
496 /***********************************************************/
497 void hw_error(const char *fmt, ...)
503 fprintf(stderr, "qemu: hardware error: ");
504 vfprintf(stderr, fmt, ap);
505 fprintf(stderr, "\n");
506 for(env = first_cpu; env != NULL; env = env->next_cpu) {
507 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
509 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
511 cpu_dump_state(env, stderr, fprintf, 0);
518 /***********************************************************/
521 static QEMUPutKBDEvent *qemu_put_kbd_event;
522 static void *qemu_put_kbd_event_opaque;
523 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
524 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
526 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
528 qemu_put_kbd_event_opaque = opaque;
529 qemu_put_kbd_event = func;
532 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
533 void *opaque, int absolute,
536 QEMUPutMouseEntry *s, *cursor;
538 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
542 s->qemu_put_mouse_event = func;
543 s->qemu_put_mouse_event_opaque = opaque;
544 s->qemu_put_mouse_event_absolute = absolute;
545 s->qemu_put_mouse_event_name = qemu_strdup(name);
548 if (!qemu_put_mouse_event_head) {
549 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
553 cursor = qemu_put_mouse_event_head;
554 while (cursor->next != NULL)
555 cursor = cursor->next;
558 qemu_put_mouse_event_current = s;
563 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
565 QEMUPutMouseEntry *prev = NULL, *cursor;
567 if (!qemu_put_mouse_event_head || entry == NULL)
570 cursor = qemu_put_mouse_event_head;
571 while (cursor != NULL && cursor != entry) {
573 cursor = cursor->next;
576 if (cursor == NULL) // does not exist or list empty
578 else if (prev == NULL) { // entry is head
579 qemu_put_mouse_event_head = cursor->next;
580 if (qemu_put_mouse_event_current == entry)
581 qemu_put_mouse_event_current = cursor->next;
582 qemu_free(entry->qemu_put_mouse_event_name);
587 prev->next = entry->next;
589 if (qemu_put_mouse_event_current == entry)
590 qemu_put_mouse_event_current = prev;
592 qemu_free(entry->qemu_put_mouse_event_name);
596 void kbd_put_keycode(int keycode)
598 if (qemu_put_kbd_event) {
599 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
603 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
605 QEMUPutMouseEvent *mouse_event;
606 void *mouse_event_opaque;
609 if (!qemu_put_mouse_event_current) {
614 qemu_put_mouse_event_current->qemu_put_mouse_event;
616 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
619 if (graphic_rotate) {
620 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
623 width = graphic_width - 1;
624 mouse_event(mouse_event_opaque,
625 width - dy, dx, dz, buttons_state);
627 mouse_event(mouse_event_opaque,
628 dx, dy, dz, buttons_state);
632 int kbd_mouse_is_absolute(void)
634 if (!qemu_put_mouse_event_current)
637 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
640 void do_info_mice(void)
642 QEMUPutMouseEntry *cursor;
645 if (!qemu_put_mouse_event_head) {
646 term_printf("No mouse devices connected\n");
650 term_printf("Mouse devices available:\n");
651 cursor = qemu_put_mouse_event_head;
652 while (cursor != NULL) {
653 term_printf("%c Mouse #%d: %s\n",
654 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
655 index, cursor->qemu_put_mouse_event_name);
657 cursor = cursor->next;
661 void do_mouse_set(int index)
663 QEMUPutMouseEntry *cursor;
666 if (!qemu_put_mouse_event_head) {
667 term_printf("No mouse devices connected\n");
671 cursor = qemu_put_mouse_event_head;
672 while (cursor != NULL && index != i) {
674 cursor = cursor->next;
678 qemu_put_mouse_event_current = cursor;
680 term_printf("Mouse at given index not found\n");
683 /* compute with 96 bit intermediate result: (a*b)/c */
684 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
689 #ifdef WORDS_BIGENDIAN
699 rl = (uint64_t)u.l.low * (uint64_t)b;
700 rh = (uint64_t)u.l.high * (uint64_t)b;
703 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
707 /***********************************************************/
708 /* real time host monotonic timer */
710 #define QEMU_TIMER_BASE 1000000000LL
714 static int64_t clock_freq;
716 static void init_get_clock(void)
720 ret = QueryPerformanceFrequency(&freq);
722 fprintf(stderr, "Could not calibrate ticks\n");
725 clock_freq = freq.QuadPart;
728 static int64_t get_clock(void)
731 QueryPerformanceCounter(&ti);
732 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
737 static int use_rt_clock;
739 static void init_get_clock(void)
742 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000)
745 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
752 static int64_t get_clock(void)
754 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000)
757 clock_gettime(CLOCK_MONOTONIC, &ts);
758 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
762 /* XXX: using gettimeofday leads to problems if the date
763 changes, so it should be avoided. */
765 gettimeofday(&tv, NULL);
766 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
771 /* Return the virtual CPU time, based on the instruction counter. */
772 static int64_t cpu_get_icount(void)
775 CPUState *env = cpu_single_env;;
776 icount = qemu_icount;
779 fprintf(stderr, "Bad clock read\n");
780 icount -= (env->icount_decr.u16.low + env->icount_extra);
782 return qemu_icount_bias + (icount << icount_time_shift);
785 /***********************************************************/
786 /* guest cycle counter */
788 static int64_t cpu_ticks_prev;
789 static int64_t cpu_ticks_offset;
790 static int64_t cpu_clock_offset;
791 static int cpu_ticks_enabled;
793 /* return the host CPU cycle counter and handle stop/restart */
794 int64_t cpu_get_ticks(void)
797 return cpu_get_icount();
799 if (!cpu_ticks_enabled) {
800 return cpu_ticks_offset;
803 ticks = cpu_get_real_ticks();
804 if (cpu_ticks_prev > ticks) {
805 /* Note: non increasing ticks may happen if the host uses
807 cpu_ticks_offset += cpu_ticks_prev - ticks;
809 cpu_ticks_prev = ticks;
810 return ticks + cpu_ticks_offset;
814 /* return the host CPU monotonic timer and handle stop/restart */
815 static int64_t cpu_get_clock(void)
818 if (!cpu_ticks_enabled) {
819 return cpu_clock_offset;
822 return ti + cpu_clock_offset;
826 /* enable cpu_get_ticks() */
827 void cpu_enable_ticks(void)
829 if (!cpu_ticks_enabled) {
830 cpu_ticks_offset -= cpu_get_real_ticks();
831 cpu_clock_offset -= get_clock();
832 cpu_ticks_enabled = 1;
836 /* disable cpu_get_ticks() : the clock is stopped. You must not call
837 cpu_get_ticks() after that. */
838 void cpu_disable_ticks(void)
840 if (cpu_ticks_enabled) {
841 cpu_ticks_offset = cpu_get_ticks();
842 cpu_clock_offset = cpu_get_clock();
843 cpu_ticks_enabled = 0;
847 /***********************************************************/
850 #define QEMU_TIMER_REALTIME 0
851 #define QEMU_TIMER_VIRTUAL 1
855 /* XXX: add frequency */
863 struct QEMUTimer *next;
866 struct qemu_alarm_timer {
870 int (*start)(struct qemu_alarm_timer *t);
871 void (*stop)(struct qemu_alarm_timer *t);
872 void (*rearm)(struct qemu_alarm_timer *t);
876 #define ALARM_FLAG_DYNTICKS 0x1
877 #define ALARM_FLAG_EXPIRED 0x2
879 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
881 return t->flags & ALARM_FLAG_DYNTICKS;
884 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
886 if (!alarm_has_dynticks(t))
892 /* TODO: MIN_TIMER_REARM_US should be optimized */
893 #define MIN_TIMER_REARM_US 250
895 static struct qemu_alarm_timer *alarm_timer;
897 static int alarm_timer_rfd, alarm_timer_wfd;
902 struct qemu_alarm_win32 {
906 } alarm_win32_data = {0, NULL, -1};
908 static int win32_start_timer(struct qemu_alarm_timer *t);
909 static void win32_stop_timer(struct qemu_alarm_timer *t);
910 static void win32_rearm_timer(struct qemu_alarm_timer *t);
914 static int unix_start_timer(struct qemu_alarm_timer *t);
915 static void unix_stop_timer(struct qemu_alarm_timer *t);
919 static int dynticks_start_timer(struct qemu_alarm_timer *t);
920 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
921 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
923 static int hpet_start_timer(struct qemu_alarm_timer *t);
924 static void hpet_stop_timer(struct qemu_alarm_timer *t);
926 static int rtc_start_timer(struct qemu_alarm_timer *t);
927 static void rtc_stop_timer(struct qemu_alarm_timer *t);
929 #endif /* __linux__ */
933 /* Correlation between real and virtual time is always going to be
934 fairly approximate, so ignore small variation.
935 When the guest is idle real and virtual time will be aligned in
937 #define ICOUNT_WOBBLE (QEMU_TIMER_BASE / 10)
939 static void icount_adjust(void)
944 static int64_t last_delta;
945 /* If the VM is not running, then do nothing. */
949 cur_time = cpu_get_clock();
950 cur_icount = qemu_get_clock(vm_clock);
951 delta = cur_icount - cur_time;
952 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
954 && last_delta + ICOUNT_WOBBLE < delta * 2
955 && icount_time_shift > 0) {
956 /* The guest is getting too far ahead. Slow time down. */
960 && last_delta - ICOUNT_WOBBLE > delta * 2
961 && icount_time_shift < MAX_ICOUNT_SHIFT) {
962 /* The guest is getting too far behind. Speed time up. */
966 qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
969 static void icount_adjust_rt(void * opaque)
971 qemu_mod_timer(icount_rt_timer,
972 qemu_get_clock(rt_clock) + 1000);
976 static void icount_adjust_vm(void * opaque)
978 qemu_mod_timer(icount_vm_timer,
979 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
983 static void init_icount_adjust(void)
985 /* Have both realtime and virtual time triggers for speed adjustment.
986 The realtime trigger catches emulated time passing too slowly,
987 the virtual time trigger catches emulated time passing too fast.
988 Realtime triggers occur even when idle, so use them less frequently
990 icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
991 qemu_mod_timer(icount_rt_timer,
992 qemu_get_clock(rt_clock) + 1000);
993 icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
994 qemu_mod_timer(icount_vm_timer,
995 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
998 static struct qemu_alarm_timer alarm_timers[] = {
1001 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
1002 dynticks_stop_timer, dynticks_rearm_timer, NULL},
1003 /* HPET - if available - is preferred */
1004 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
1005 /* ...otherwise try RTC */
1006 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
1008 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
1010 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
1011 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
1012 {"win32", 0, win32_start_timer,
1013 win32_stop_timer, NULL, &alarm_win32_data},
1018 static void show_available_alarms(void)
1022 printf("Available alarm timers, in order of precedence:\n");
1023 for (i = 0; alarm_timers[i].name; i++)
1024 printf("%s\n", alarm_timers[i].name);
1027 static void configure_alarms(char const *opt)
1031 int count = (sizeof(alarm_timers) / sizeof(*alarm_timers)) - 1;
1034 struct qemu_alarm_timer tmp;
1036 if (!strcmp(opt, "?")) {
1037 show_available_alarms();
1043 /* Reorder the array */
1044 name = strtok(arg, ",");
1046 for (i = 0; i < count && alarm_timers[i].name; i++) {
1047 if (!strcmp(alarm_timers[i].name, name))
1052 fprintf(stderr, "Unknown clock %s\n", name);
1061 tmp = alarm_timers[i];
1062 alarm_timers[i] = alarm_timers[cur];
1063 alarm_timers[cur] = tmp;
1067 name = strtok(NULL, ",");
1073 /* Disable remaining timers */
1074 for (i = cur; i < count; i++)
1075 alarm_timers[i].name = NULL;
1077 show_available_alarms();
1082 QEMUClock *rt_clock;
1083 QEMUClock *vm_clock;
1085 static QEMUTimer *active_timers[2];
1087 static QEMUClock *qemu_new_clock(int type)
1090 clock = qemu_mallocz(sizeof(QEMUClock));
1097 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
1101 ts = qemu_mallocz(sizeof(QEMUTimer));
1104 ts->opaque = opaque;
1108 void qemu_free_timer(QEMUTimer *ts)
1113 /* stop a timer, but do not dealloc it */
1114 void qemu_del_timer(QEMUTimer *ts)
1118 /* NOTE: this code must be signal safe because
1119 qemu_timer_expired() can be called from a signal. */
1120 pt = &active_timers[ts->clock->type];
1133 /* modify the current timer so that it will be fired when current_time
1134 >= expire_time. The corresponding callback will be called. */
1135 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
1141 /* add the timer in the sorted list */
1142 /* NOTE: this code must be signal safe because
1143 qemu_timer_expired() can be called from a signal. */
1144 pt = &active_timers[ts->clock->type];
1149 if (t->expire_time > expire_time)
1153 ts->expire_time = expire_time;
1157 /* Rearm if necessary */
1158 if (pt == &active_timers[ts->clock->type]) {
1159 if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0) {
1160 qemu_rearm_alarm_timer(alarm_timer);
1162 /* Interrupt execution to force deadline recalculation. */
1163 if (use_icount && cpu_single_env) {
1164 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
1169 int qemu_timer_pending(QEMUTimer *ts)
1172 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1179 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1183 return (timer_head->expire_time <= current_time);
1186 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1192 if (!ts || ts->expire_time > current_time)
1194 /* remove timer from the list before calling the callback */
1195 *ptimer_head = ts->next;
1198 /* run the callback (the timer list can be modified) */
1203 int64_t qemu_get_clock(QEMUClock *clock)
1205 switch(clock->type) {
1206 case QEMU_TIMER_REALTIME:
1207 return get_clock() / 1000000;
1209 case QEMU_TIMER_VIRTUAL:
1211 return cpu_get_icount();
1213 return cpu_get_clock();
1218 static void init_timers(void)
1221 ticks_per_sec = QEMU_TIMER_BASE;
1222 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1223 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1227 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1229 uint64_t expire_time;
1231 if (qemu_timer_pending(ts)) {
1232 expire_time = ts->expire_time;
1236 qemu_put_be64(f, expire_time);
1239 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1241 uint64_t expire_time;
1243 expire_time = qemu_get_be64(f);
1244 if (expire_time != -1) {
1245 qemu_mod_timer(ts, expire_time);
1251 static void timer_save(QEMUFile *f, void *opaque)
1253 if (cpu_ticks_enabled) {
1254 hw_error("cannot save state if virtual timers are running");
1256 qemu_put_be64(f, cpu_ticks_offset);
1257 qemu_put_be64(f, ticks_per_sec);
1258 qemu_put_be64(f, cpu_clock_offset);
1261 static int timer_load(QEMUFile *f, void *opaque, int version_id)
1263 if (version_id != 1 && version_id != 2)
1265 if (cpu_ticks_enabled) {
1268 cpu_ticks_offset=qemu_get_be64(f);
1269 ticks_per_sec=qemu_get_be64(f);
1270 if (version_id == 2) {
1271 cpu_clock_offset=qemu_get_be64(f);
1277 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1278 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
1280 static void host_alarm_handler(int host_signum)
1284 #define DISP_FREQ 1000
1286 static int64_t delta_min = INT64_MAX;
1287 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1289 ti = qemu_get_clock(vm_clock);
1290 if (last_clock != 0) {
1291 delta = ti - last_clock;
1292 if (delta < delta_min)
1294 if (delta > delta_max)
1297 if (++count == DISP_FREQ) {
1298 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1299 muldiv64(delta_min, 1000000, ticks_per_sec),
1300 muldiv64(delta_max, 1000000, ticks_per_sec),
1301 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1302 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1304 delta_min = INT64_MAX;
1312 if (alarm_has_dynticks(alarm_timer) ||
1314 qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1315 qemu_get_clock(vm_clock))) ||
1316 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1317 qemu_get_clock(rt_clock))) {
1318 CPUState *env = next_cpu;
1321 struct qemu_alarm_win32 *data = ((struct qemu_alarm_timer*)dwUser)->priv;
1322 SetEvent(data->host_alarm);
1324 static const char byte = 0;
1325 write(alarm_timer_wfd, &byte, sizeof(byte));
1327 alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1330 /* stop the currently executing cpu because a timer occured */
1331 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
1333 if (env->kqemu_enabled) {
1334 kqemu_cpu_interrupt(env);
1342 static int64_t qemu_next_deadline(void)
1346 if (active_timers[QEMU_TIMER_VIRTUAL]) {
1347 delta = active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1348 qemu_get_clock(vm_clock);
1350 /* To avoid problems with overflow limit this to 2^32. */
1360 #if defined(__linux__) || defined(_WIN32)
1361 static uint64_t qemu_next_deadline_dyntick(void)
1369 delta = (qemu_next_deadline() + 999) / 1000;
1371 if (active_timers[QEMU_TIMER_REALTIME]) {
1372 rtdelta = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1373 qemu_get_clock(rt_clock))*1000;
1374 if (rtdelta < delta)
1378 if (delta < MIN_TIMER_REARM_US)
1379 delta = MIN_TIMER_REARM_US;
1387 /* Sets a specific flag */
1388 static int fcntl_setfl(int fd, int flag)
1392 flags = fcntl(fd, F_GETFL);
1396 if (fcntl(fd, F_SETFL, flags | flag) == -1)
1402 #if defined(__linux__)
1404 #define RTC_FREQ 1024
1406 static void enable_sigio_timer(int fd)
1408 struct sigaction act;
1411 sigfillset(&act.sa_mask);
1413 act.sa_handler = host_alarm_handler;
1415 sigaction(SIGIO, &act, NULL);
1416 fcntl_setfl(fd, O_ASYNC);
1417 fcntl(fd, F_SETOWN, getpid());
1420 static int hpet_start_timer(struct qemu_alarm_timer *t)
1422 struct hpet_info info;
1425 fd = open("/dev/hpet", O_RDONLY);
1430 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1432 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1433 "error, but for better emulation accuracy type:\n"
1434 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1438 /* Check capabilities */
1439 r = ioctl(fd, HPET_INFO, &info);
1443 /* Enable periodic mode */
1444 r = ioctl(fd, HPET_EPI, 0);
1445 if (info.hi_flags && (r < 0))
1448 /* Enable interrupt */
1449 r = ioctl(fd, HPET_IE_ON, 0);
1453 enable_sigio_timer(fd);
1454 t->priv = (void *)(long)fd;
1462 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1464 int fd = (long)t->priv;
1469 static int rtc_start_timer(struct qemu_alarm_timer *t)
1472 unsigned long current_rtc_freq = 0;
1474 TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1477 ioctl(rtc_fd, RTC_IRQP_READ, ¤t_rtc_freq);
1478 if (current_rtc_freq != RTC_FREQ &&
1479 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1480 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1481 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1482 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1485 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1491 enable_sigio_timer(rtc_fd);
1493 t->priv = (void *)(long)rtc_fd;
1498 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1500 int rtc_fd = (long)t->priv;
1505 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1509 struct sigaction act;
1511 sigfillset(&act.sa_mask);
1513 act.sa_handler = host_alarm_handler;
1515 sigaction(SIGALRM, &act, NULL);
1517 ev.sigev_value.sival_int = 0;
1518 ev.sigev_notify = SIGEV_SIGNAL;
1519 ev.sigev_signo = SIGALRM;
1521 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1522 perror("timer_create");
1524 /* disable dynticks */
1525 fprintf(stderr, "Dynamic Ticks disabled\n");
1530 t->priv = (void *)host_timer;
1535 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1537 timer_t host_timer = (timer_t)t->priv;
1539 timer_delete(host_timer);
1542 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1544 timer_t host_timer = (timer_t)t->priv;
1545 struct itimerspec timeout;
1546 int64_t nearest_delta_us = INT64_MAX;
1549 if (!active_timers[QEMU_TIMER_REALTIME] &&
1550 !active_timers[QEMU_TIMER_VIRTUAL])
1553 nearest_delta_us = qemu_next_deadline_dyntick();
1555 /* check whether a timer is already running */
1556 if (timer_gettime(host_timer, &timeout)) {
1558 fprintf(stderr, "Internal timer error: aborting\n");
1561 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1562 if (current_us && current_us <= nearest_delta_us)
1565 timeout.it_interval.tv_sec = 0;
1566 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1567 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1568 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1569 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1571 fprintf(stderr, "Internal timer error: aborting\n");
1576 #endif /* defined(__linux__) */
1578 static int unix_start_timer(struct qemu_alarm_timer *t)
1580 struct sigaction act;
1581 struct itimerval itv;
1585 sigfillset(&act.sa_mask);
1587 act.sa_handler = host_alarm_handler;
1589 sigaction(SIGALRM, &act, NULL);
1591 itv.it_interval.tv_sec = 0;
1592 /* for i386 kernel 2.6 to get 1 ms */
1593 itv.it_interval.tv_usec = 999;
1594 itv.it_value.tv_sec = 0;
1595 itv.it_value.tv_usec = 10 * 1000;
1597 err = setitimer(ITIMER_REAL, &itv, NULL);
1604 static void unix_stop_timer(struct qemu_alarm_timer *t)
1606 struct itimerval itv;
1608 memset(&itv, 0, sizeof(itv));
1609 setitimer(ITIMER_REAL, &itv, NULL);
1612 #endif /* !defined(_WIN32) */
1614 static void try_to_rearm_timer(void *opaque)
1616 struct qemu_alarm_timer *t = opaque;
1620 /* Drain the notify pipe */
1623 len = read(alarm_timer_rfd, buffer, sizeof(buffer));
1624 } while ((len == -1 && errno == EINTR) || len > 0);
1627 /* vm time timers */
1628 if (vm_running && likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))
1629 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
1630 qemu_get_clock(vm_clock));
1632 /* real time timers */
1633 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
1634 qemu_get_clock(rt_clock));
1636 if (t->flags & ALARM_FLAG_EXPIRED) {
1637 alarm_timer->flags &= ~ALARM_FLAG_EXPIRED;
1638 qemu_rearm_alarm_timer(alarm_timer);
1644 static int win32_start_timer(struct qemu_alarm_timer *t)
1647 struct qemu_alarm_win32 *data = t->priv;
1650 data->host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1651 if (!data->host_alarm) {
1652 perror("Failed CreateEvent");
1656 memset(&tc, 0, sizeof(tc));
1657 timeGetDevCaps(&tc, sizeof(tc));
1659 if (data->period < tc.wPeriodMin)
1660 data->period = tc.wPeriodMin;
1662 timeBeginPeriod(data->period);
1664 flags = TIME_CALLBACK_FUNCTION;
1665 if (alarm_has_dynticks(t))
1666 flags |= TIME_ONESHOT;
1668 flags |= TIME_PERIODIC;
1670 data->timerId = timeSetEvent(1, // interval (ms)
1671 data->period, // resolution
1672 host_alarm_handler, // function
1673 (DWORD)t, // parameter
1676 if (!data->timerId) {
1677 perror("Failed to initialize win32 alarm timer");
1679 timeEndPeriod(data->period);
1680 CloseHandle(data->host_alarm);
1684 qemu_add_wait_object(data->host_alarm, try_to_rearm_timer, t);
1689 static void win32_stop_timer(struct qemu_alarm_timer *t)
1691 struct qemu_alarm_win32 *data = t->priv;
1693 timeKillEvent(data->timerId);
1694 timeEndPeriod(data->period);
1696 CloseHandle(data->host_alarm);
1699 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1701 struct qemu_alarm_win32 *data = t->priv;
1702 uint64_t nearest_delta_us;
1704 if (!active_timers[QEMU_TIMER_REALTIME] &&
1705 !active_timers[QEMU_TIMER_VIRTUAL])
1708 nearest_delta_us = qemu_next_deadline_dyntick();
1709 nearest_delta_us /= 1000;
1711 timeKillEvent(data->timerId);
1713 data->timerId = timeSetEvent(1,
1717 TIME_ONESHOT | TIME_PERIODIC);
1719 if (!data->timerId) {
1720 perror("Failed to re-arm win32 alarm timer");
1722 timeEndPeriod(data->period);
1723 CloseHandle(data->host_alarm);
1730 static int init_timer_alarm(void)
1732 struct qemu_alarm_timer *t = NULL;
1742 err = fcntl_setfl(fds[0], O_NONBLOCK);
1746 err = fcntl_setfl(fds[1], O_NONBLOCK);
1750 alarm_timer_rfd = fds[0];
1751 alarm_timer_wfd = fds[1];
1754 for (i = 0; alarm_timers[i].name; i++) {
1755 t = &alarm_timers[i];
1768 qemu_set_fd_handler2(alarm_timer_rfd, NULL,
1769 try_to_rearm_timer, NULL, t);
1784 static void quit_timers(void)
1786 alarm_timer->stop(alarm_timer);
1790 /***********************************************************/
1791 /* host time/date access */
1792 void qemu_get_timedate(struct tm *tm, int offset)
1799 if (rtc_date_offset == -1) {
1803 ret = localtime(&ti);
1805 ti -= rtc_date_offset;
1809 memcpy(tm, ret, sizeof(struct tm));
1812 int qemu_timedate_diff(struct tm *tm)
1816 if (rtc_date_offset == -1)
1818 seconds = mktimegm(tm);
1820 seconds = mktime(tm);
1822 seconds = mktimegm(tm) + rtc_date_offset;
1824 return seconds - time(NULL);
1828 static void socket_cleanup(void)
1833 static int socket_init(void)
1838 ret = WSAStartup(MAKEWORD(2,2), &Data);
1840 err = WSAGetLastError();
1841 fprintf(stderr, "WSAStartup: %d\n", err);
1844 atexit(socket_cleanup);
1849 const char *get_opt_name(char *buf, int buf_size, const char *p)
1854 while (*p != '\0' && *p != '=') {
1855 if (q && (q - buf) < buf_size - 1)
1865 const char *get_opt_value(char *buf, int buf_size, const char *p)
1870 while (*p != '\0') {
1872 if (*(p + 1) != ',')
1876 if (q && (q - buf) < buf_size - 1)
1886 int get_param_value(char *buf, int buf_size,
1887 const char *tag, const char *str)
1894 p = get_opt_name(option, sizeof(option), p);
1898 if (!strcmp(tag, option)) {
1899 (void)get_opt_value(buf, buf_size, p);
1902 p = get_opt_value(NULL, 0, p);
1911 int check_params(char *buf, int buf_size,
1912 const char * const *params, const char *str)
1919 p = get_opt_name(buf, buf_size, p);
1923 for(i = 0; params[i] != NULL; i++)
1924 if (!strcmp(params[i], buf))
1926 if (params[i] == NULL)
1928 p = get_opt_value(NULL, 0, p);
1936 /***********************************************************/
1937 /* Bluetooth support */
1940 static struct HCIInfo *hci_table[MAX_NICS];
1942 static struct bt_vlan_s {
1943 struct bt_scatternet_s net;
1945 struct bt_vlan_s *next;
1948 /* find or alloc a new bluetooth "VLAN" */
1949 static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
1951 struct bt_vlan_s **pvlan, *vlan;
1952 for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
1956 vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
1958 pvlan = &first_bt_vlan;
1959 while (*pvlan != NULL)
1960 pvlan = &(*pvlan)->next;
1965 static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
1969 static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
1974 static struct HCIInfo null_hci = {
1975 .cmd_send = null_hci_send,
1976 .sco_send = null_hci_send,
1977 .acl_send = null_hci_send,
1978 .bdaddr_set = null_hci_addr_set,
1981 struct HCIInfo *qemu_next_hci(void)
1983 if (cur_hci == nb_hcis)
1986 return hci_table[cur_hci++];
1989 static struct HCIInfo *hci_init(const char *str)
1992 struct bt_scatternet_s *vlan = 0;
1994 if (!strcmp(str, "null"))
1997 else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
1999 return bt_host_hci(str[4] ? str + 5 : "hci0");
2000 else if (!strncmp(str, "hci", 3)) {
2003 if (!strncmp(str + 3, ",vlan=", 6)) {
2004 vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
2009 vlan = qemu_find_bt_vlan(0);
2011 return bt_new_hci(vlan);
2014 fprintf(stderr, "qemu: Unknown bluetooth HCI `%s'.\n", str);
2019 static int bt_hci_parse(const char *str)
2021 struct HCIInfo *hci;
2024 if (nb_hcis >= MAX_NICS) {
2025 fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
2029 hci = hci_init(str);
2038 bdaddr.b[5] = 0x56 + nb_hcis;
2039 hci->bdaddr_set(hci, bdaddr.b);
2041 hci_table[nb_hcis++] = hci;
2046 static void bt_vhci_add(int vlan_id)
2048 struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
2051 fprintf(stderr, "qemu: warning: adding a VHCI to "
2052 "an empty scatternet %i\n", vlan_id);
2054 bt_vhci_init(bt_new_hci(vlan));
2057 static struct bt_device_s *bt_device_add(const char *opt)
2059 struct bt_scatternet_s *vlan;
2061 char *endp = strstr(opt, ",vlan=");
2062 int len = (endp ? endp - opt : strlen(opt)) + 1;
2065 pstrcpy(devname, MIN(sizeof(devname), len), opt);
2068 vlan_id = strtol(endp + 6, &endp, 0);
2070 fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
2075 vlan = qemu_find_bt_vlan(vlan_id);
2078 fprintf(stderr, "qemu: warning: adding a slave device to "
2079 "an empty scatternet %i\n", vlan_id);
2081 if (!strcmp(devname, "keyboard"))
2082 return bt_keyboard_init(vlan);
2084 fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
2088 static int bt_parse(const char *opt)
2090 const char *endp, *p;
2093 if (strstart(opt, "hci", &endp)) {
2094 if (!*endp || *endp == ',') {
2096 if (!strstart(endp, ",vlan=", 0))
2099 return bt_hci_parse(opt);
2101 } else if (strstart(opt, "vhci", &endp)) {
2102 if (!*endp || *endp == ',') {
2104 if (strstart(endp, ",vlan=", &p)) {
2105 vlan = strtol(p, (char **) &endp, 0);
2107 fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
2111 fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
2120 } else if (strstart(opt, "device:", &endp))
2121 return !bt_device_add(endp);
2123 fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
2127 /***********************************************************/
2128 /* QEMU Block devices */
2130 #define HD_ALIAS "index=%d,media=disk"
2132 #define CDROM_ALIAS "index=1,media=cdrom"
2134 #define CDROM_ALIAS "index=2,media=cdrom"
2136 #define FD_ALIAS "index=%d,if=floppy"
2137 #define PFLASH_ALIAS "if=pflash"
2138 #define MTD_ALIAS "if=mtd"
2139 #define SD_ALIAS "index=0,if=sd"
2141 static int drive_add(const char *file, const char *fmt, ...)
2145 if (nb_drives_opt >= MAX_DRIVES) {
2146 fprintf(stderr, "qemu: too many drives\n");
2150 drives_opt[nb_drives_opt].file = file;
2152 vsnprintf(drives_opt[nb_drives_opt].opt,
2153 sizeof(drives_opt[0].opt), fmt, ap);
2156 return nb_drives_opt++;
2159 int drive_get_index(BlockInterfaceType type, int bus, int unit)
2163 /* seek interface, bus and unit */
2165 for (index = 0; index < nb_drives; index++)
2166 if (drives_table[index].type == type &&
2167 drives_table[index].bus == bus &&
2168 drives_table[index].unit == unit)
2174 int drive_get_max_bus(BlockInterfaceType type)
2180 for (index = 0; index < nb_drives; index++) {
2181 if(drives_table[index].type == type &&
2182 drives_table[index].bus > max_bus)
2183 max_bus = drives_table[index].bus;
2188 static void bdrv_format_print(void *opaque, const char *name)
2190 fprintf(stderr, " %s", name);
2193 static int drive_init(struct drive_opt *arg, int snapshot,
2194 QEMUMachine *machine)
2199 const char *mediastr = "";
2200 BlockInterfaceType type;
2201 enum { MEDIA_DISK, MEDIA_CDROM } media;
2202 int bus_id, unit_id;
2203 int cyls, heads, secs, translation;
2204 BlockDriverState *bdrv;
2205 BlockDriver *drv = NULL;
2210 char *str = arg->opt;
2211 static const char * const params[] = { "bus", "unit", "if", "index",
2212 "cyls", "heads", "secs", "trans",
2213 "media", "snapshot", "file",
2214 "cache", "format", NULL };
2216 if (check_params(buf, sizeof(buf), params, str) < 0) {
2217 fprintf(stderr, "qemu: unknown parameter '%s' in '%s'\n",
2223 cyls = heads = secs = 0;
2226 translation = BIOS_ATA_TRANSLATION_AUTO;
2230 if (machine->use_scsi) {
2232 max_devs = MAX_SCSI_DEVS;
2233 pstrcpy(devname, sizeof(devname), "scsi");
2236 max_devs = MAX_IDE_DEVS;
2237 pstrcpy(devname, sizeof(devname), "ide");
2241 /* extract parameters */
2243 if (get_param_value(buf, sizeof(buf), "bus", str)) {
2244 bus_id = strtol(buf, NULL, 0);
2246 fprintf(stderr, "qemu: '%s' invalid bus id\n", str);
2251 if (get_param_value(buf, sizeof(buf), "unit", str)) {
2252 unit_id = strtol(buf, NULL, 0);
2254 fprintf(stderr, "qemu: '%s' invalid unit id\n", str);
2259 if (get_param_value(buf, sizeof(buf), "if", str)) {
2260 pstrcpy(devname, sizeof(devname), buf);
2261 if (!strcmp(buf, "ide")) {
2263 max_devs = MAX_IDE_DEVS;
2264 } else if (!strcmp(buf, "scsi")) {
2266 max_devs = MAX_SCSI_DEVS;
2267 } else if (!strcmp(buf, "floppy")) {
2270 } else if (!strcmp(buf, "pflash")) {
2273 } else if (!strcmp(buf, "mtd")) {
2276 } else if (!strcmp(buf, "sd")) {
2280 fprintf(stderr, "qemu: '%s' unsupported bus type '%s'\n", str, buf);
2285 if (get_param_value(buf, sizeof(buf), "index", str)) {
2286 index = strtol(buf, NULL, 0);
2288 fprintf(stderr, "qemu: '%s' invalid index\n", str);
2293 if (get_param_value(buf, sizeof(buf), "cyls", str)) {
2294 cyls = strtol(buf, NULL, 0);
2297 if (get_param_value(buf, sizeof(buf), "heads", str)) {
2298 heads = strtol(buf, NULL, 0);
2301 if (get_param_value(buf, sizeof(buf), "secs", str)) {
2302 secs = strtol(buf, NULL, 0);
2305 if (cyls || heads || secs) {
2306 if (cyls < 1 || cyls > 16383) {
2307 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", str);
2310 if (heads < 1 || heads > 16) {
2311 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", str);
2314 if (secs < 1 || secs > 63) {
2315 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", str);
2320 if (get_param_value(buf, sizeof(buf), "trans", str)) {
2323 "qemu: '%s' trans must be used with cyls,heads and secs\n",
2327 if (!strcmp(buf, "none"))
2328 translation = BIOS_ATA_TRANSLATION_NONE;
2329 else if (!strcmp(buf, "lba"))
2330 translation = BIOS_ATA_TRANSLATION_LBA;
2331 else if (!strcmp(buf, "auto"))
2332 translation = BIOS_ATA_TRANSLATION_AUTO;
2334 fprintf(stderr, "qemu: '%s' invalid translation type\n", str);
2339 if (get_param_value(buf, sizeof(buf), "media", str)) {
2340 if (!strcmp(buf, "disk")) {
2342 } else if (!strcmp(buf, "cdrom")) {
2343 if (cyls || secs || heads) {
2345 "qemu: '%s' invalid physical CHS format\n", str);
2348 media = MEDIA_CDROM;
2350 fprintf(stderr, "qemu: '%s' invalid media\n", str);
2355 if (get_param_value(buf, sizeof(buf), "snapshot", str)) {
2356 if (!strcmp(buf, "on"))
2358 else if (!strcmp(buf, "off"))
2361 fprintf(stderr, "qemu: '%s' invalid snapshot option\n", str);
2366 if (get_param_value(buf, sizeof(buf), "cache", str)) {
2367 if (!strcmp(buf, "off") || !strcmp(buf, "none"))
2369 else if (!strcmp(buf, "writethrough"))
2371 else if (!strcmp(buf, "writeback"))
2374 fprintf(stderr, "qemu: invalid cache option\n");
2379 if (get_param_value(buf, sizeof(buf), "format", str)) {
2380 if (strcmp(buf, "?") == 0) {
2381 fprintf(stderr, "qemu: Supported formats:");
2382 bdrv_iterate_format(bdrv_format_print, NULL);
2383 fprintf(stderr, "\n");
2386 drv = bdrv_find_format(buf);
2388 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
2393 if (arg->file == NULL)
2394 get_param_value(file, sizeof(file), "file", str);
2396 pstrcpy(file, sizeof(file), arg->file);
2398 /* compute bus and unit according index */
2401 if (bus_id != 0 || unit_id != -1) {
2403 "qemu: '%s' index cannot be used with bus and unit\n", str);
2411 unit_id = index % max_devs;
2412 bus_id = index / max_devs;
2416 /* if user doesn't specify a unit_id,
2417 * try to find the first free
2420 if (unit_id == -1) {
2422 while (drive_get_index(type, bus_id, unit_id) != -1) {
2424 if (max_devs && unit_id >= max_devs) {
2425 unit_id -= max_devs;
2433 if (max_devs && unit_id >= max_devs) {
2434 fprintf(stderr, "qemu: '%s' unit %d too big (max is %d)\n",
2435 str, unit_id, max_devs - 1);
2440 * ignore multiple definitions
2443 if (drive_get_index(type, bus_id, unit_id) != -1)
2448 if (type == IF_IDE || type == IF_SCSI)
2449 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
2451 snprintf(buf, sizeof(buf), "%s%i%s%i",
2452 devname, bus_id, mediastr, unit_id);
2454 snprintf(buf, sizeof(buf), "%s%s%i",
2455 devname, mediastr, unit_id);
2456 bdrv = bdrv_new(buf);
2457 drives_table[nb_drives].bdrv = bdrv;
2458 drives_table[nb_drives].type = type;
2459 drives_table[nb_drives].bus = bus_id;
2460 drives_table[nb_drives].unit = unit_id;
2469 bdrv_set_geometry_hint(bdrv, cyls, heads, secs);
2470 bdrv_set_translation_hint(bdrv, translation);
2474 bdrv_set_type_hint(bdrv, BDRV_TYPE_CDROM);
2479 /* FIXME: This isn't really a floppy, but it's a reasonable
2482 bdrv_set_type_hint(bdrv, BDRV_TYPE_FLOPPY);
2492 bdrv_flags |= BDRV_O_SNAPSHOT;
2493 cache = 2; /* always use write-back with snapshot */
2495 if (cache == 0) /* no caching */
2496 bdrv_flags |= BDRV_O_NOCACHE;
2497 else if (cache == 2) /* write-back */
2498 bdrv_flags |= BDRV_O_CACHE_WB;
2499 if (bdrv_open2(bdrv, file, bdrv_flags, drv) < 0 || qemu_key_check(bdrv, file)) {
2500 fprintf(stderr, "qemu: could not open disk image %s\n",
2507 /***********************************************************/
2510 static USBPort *used_usb_ports;
2511 static USBPort *free_usb_ports;
2513 /* ??? Maybe change this to register a hub to keep track of the topology. */
2514 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
2515 usb_attachfn attach)
2517 port->opaque = opaque;
2518 port->index = index;
2519 port->attach = attach;
2520 port->next = free_usb_ports;
2521 free_usb_ports = port;
2524 int usb_device_add_dev(USBDevice *dev)
2528 /* Find a USB port to add the device to. */
2529 port = free_usb_ports;
2533 /* Create a new hub and chain it on. */
2534 free_usb_ports = NULL;
2535 port->next = used_usb_ports;
2536 used_usb_ports = port;
2538 hub = usb_hub_init(VM_USB_HUB_SIZE);
2539 usb_attach(port, hub);
2540 port = free_usb_ports;
2543 free_usb_ports = port->next;
2544 port->next = used_usb_ports;
2545 used_usb_ports = port;
2546 usb_attach(port, dev);
2550 static int usb_device_add(const char *devname)
2555 if (!free_usb_ports)
2558 if (strstart(devname, "host:", &p)) {
2559 dev = usb_host_device_open(p);
2560 } else if (!strcmp(devname, "mouse")) {
2561 dev = usb_mouse_init();
2562 } else if (!strcmp(devname, "tablet")) {
2563 dev = usb_tablet_init();
2564 } else if (!strcmp(devname, "keyboard")) {
2565 dev = usb_keyboard_init();
2566 } else if (strstart(devname, "disk:", &p)) {
2567 dev = usb_msd_init(p);
2568 } else if (!strcmp(devname, "wacom-tablet")) {
2569 dev = usb_wacom_init();
2570 } else if (strstart(devname, "serial:", &p)) {
2571 dev = usb_serial_init(p);
2572 #ifdef CONFIG_BRLAPI
2573 } else if (!strcmp(devname, "braille")) {
2574 dev = usb_baum_init();
2576 } else if (strstart(devname, "net:", &p)) {
2579 if (net_client_init("nic", p) < 0)
2581 nd_table[nic].model = "usb";
2582 dev = usb_net_init(&nd_table[nic]);
2583 } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
2584 dev = usb_bt_init(devname[2] ? hci_init(p) :
2585 bt_new_hci(qemu_find_bt_vlan(0)));
2592 return usb_device_add_dev(dev);
2595 int usb_device_del_addr(int bus_num, int addr)
2601 if (!used_usb_ports)
2607 lastp = &used_usb_ports;
2608 port = used_usb_ports;
2609 while (port && port->dev->addr != addr) {
2610 lastp = &port->next;
2618 *lastp = port->next;
2619 usb_attach(port, NULL);
2620 dev->handle_destroy(dev);
2621 port->next = free_usb_ports;
2622 free_usb_ports = port;
2626 static int usb_device_del(const char *devname)
2631 if (strstart(devname, "host:", &p))
2632 return usb_host_device_close(p);
2634 if (!used_usb_ports)
2637 p = strchr(devname, '.');
2640 bus_num = strtoul(devname, NULL, 0);
2641 addr = strtoul(p + 1, NULL, 0);
2643 return usb_device_del_addr(bus_num, addr);
2646 void do_usb_add(const char *devname)
2648 usb_device_add(devname);
2651 void do_usb_del(const char *devname)
2653 usb_device_del(devname);
2660 const char *speed_str;
2663 term_printf("USB support not enabled\n");
2667 for (port = used_usb_ports; port; port = port->next) {
2671 switch(dev->speed) {
2675 case USB_SPEED_FULL:
2678 case USB_SPEED_HIGH:
2685 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
2686 0, dev->addr, speed_str, dev->devname);
2690 /***********************************************************/
2691 /* PCMCIA/Cardbus */
2693 static struct pcmcia_socket_entry_s {
2694 struct pcmcia_socket_s *socket;
2695 struct pcmcia_socket_entry_s *next;
2696 } *pcmcia_sockets = 0;
2698 void pcmcia_socket_register(struct pcmcia_socket_s *socket)
2700 struct pcmcia_socket_entry_s *entry;
2702 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2703 entry->socket = socket;
2704 entry->next = pcmcia_sockets;
2705 pcmcia_sockets = entry;
2708 void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
2710 struct pcmcia_socket_entry_s *entry, **ptr;
2712 ptr = &pcmcia_sockets;
2713 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2714 if (entry->socket == socket) {
2720 void pcmcia_info(void)
2722 struct pcmcia_socket_entry_s *iter;
2723 if (!pcmcia_sockets)
2724 term_printf("No PCMCIA sockets\n");
2726 for (iter = pcmcia_sockets; iter; iter = iter->next)
2727 term_printf("%s: %s\n", iter->socket->slot_string,
2728 iter->socket->attached ? iter->socket->card_string :
2732 /***********************************************************/
2735 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
2739 static void dumb_resize(DisplayState *ds, int w, int h)
2743 static void dumb_display_init(DisplayState *ds)
2748 ds->dpy_update = dumb_update;
2749 ds->dpy_resize = dumb_resize;
2750 ds->dpy_refresh = NULL;
2751 ds->gui_timer_interval = 0;
2755 /***********************************************************/
2758 #define MAX_IO_HANDLERS 64
2760 typedef struct IOHandlerRecord {
2762 IOCanRWHandler *fd_read_poll;
2764 IOHandler *fd_write;
2767 /* temporary data */
2769 struct IOHandlerRecord *next;
2772 static IOHandlerRecord *first_io_handler;
2774 /* XXX: fd_read_poll should be suppressed, but an API change is
2775 necessary in the character devices to suppress fd_can_read(). */
2776 int qemu_set_fd_handler2(int fd,
2777 IOCanRWHandler *fd_read_poll,
2779 IOHandler *fd_write,
2782 IOHandlerRecord **pioh, *ioh;
2784 if (!fd_read && !fd_write) {
2785 pioh = &first_io_handler;
2790 if (ioh->fd == fd) {
2797 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2801 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
2804 ioh->next = first_io_handler;
2805 first_io_handler = ioh;
2808 ioh->fd_read_poll = fd_read_poll;
2809 ioh->fd_read = fd_read;
2810 ioh->fd_write = fd_write;
2811 ioh->opaque = opaque;
2817 int qemu_set_fd_handler(int fd,
2819 IOHandler *fd_write,
2822 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
2826 /***********************************************************/
2827 /* Polling handling */
2829 typedef struct PollingEntry {
2832 struct PollingEntry *next;
2835 static PollingEntry *first_polling_entry;
2837 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
2839 PollingEntry **ppe, *pe;
2840 pe = qemu_mallocz(sizeof(PollingEntry));
2844 pe->opaque = opaque;
2845 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
2850 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
2852 PollingEntry **ppe, *pe;
2853 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
2855 if (pe->func == func && pe->opaque == opaque) {
2863 /***********************************************************/
2864 /* Wait objects support */
2865 typedef struct WaitObjects {
2867 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
2868 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
2869 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
2872 static WaitObjects wait_objects = {0};
2874 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2876 WaitObjects *w = &wait_objects;
2878 if (w->num >= MAXIMUM_WAIT_OBJECTS)
2880 w->events[w->num] = handle;
2881 w->func[w->num] = func;
2882 w->opaque[w->num] = opaque;
2887 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2890 WaitObjects *w = &wait_objects;
2893 for (i = 0; i < w->num; i++) {
2894 if (w->events[i] == handle)
2897 w->events[i] = w->events[i + 1];
2898 w->func[i] = w->func[i + 1];
2899 w->opaque[i] = w->opaque[i + 1];
2907 #define SELF_ANNOUNCE_ROUNDS 5
2908 #define ETH_P_EXPERIMENTAL 0x01F1 /* just a number */
2909 //#define ETH_P_EXPERIMENTAL 0x0012 /* make it the size of the packet */
2910 #define EXPERIMENTAL_MAGIC 0xf1f23f4f
2912 static int announce_self_create(uint8_t *buf,
2915 uint32_t magic = EXPERIMENTAL_MAGIC;
2916 uint16_t proto = htons(ETH_P_EXPERIMENTAL);
2918 /* FIXME: should we send a different packet (arp/rarp/ping)? */
2920 memset(buf, 0xff, 6); /* h_dst */
2921 memcpy(buf + 6, mac_addr, 6); /* h_src */
2922 memcpy(buf + 12, &proto, 2); /* h_proto */
2923 memcpy(buf + 14, &magic, 4); /* magic */
2925 return 18; /* len */
2928 void qemu_announce_self(void)
2932 VLANClientState *vc;
2935 for (i = 0; i < nb_nics; i++) {
2936 len = announce_self_create(buf, nd_table[i].macaddr);
2937 vlan = nd_table[i].vlan;
2938 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
2939 for (j=0; j < SELF_ANNOUNCE_ROUNDS; j++)
2940 vc->fd_read(vc->opaque, buf, len);
2945 /***********************************************************/
2946 /* savevm/loadvm support */
2948 #define IO_BUF_SIZE 32768
2951 QEMUFilePutBufferFunc *put_buffer;
2952 QEMUFileGetBufferFunc *get_buffer;
2953 QEMUFileCloseFunc *close;
2954 QEMUFileRateLimit *rate_limit;
2958 int64_t buf_offset; /* start of buffer when writing, end of buffer
2961 int buf_size; /* 0 when writing */
2962 uint8_t buf[IO_BUF_SIZE];
2967 typedef struct QEMUFilePopen
2973 typedef struct QEMUFileSocket
2979 static int socket_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)
2981 QEMUFileSocket *s = opaque;
2985 len = recv(s->fd, buf, size, 0);
2986 } while (len == -1 && socket_error() == EINTR);
2989 len = -socket_error();
2994 static int socket_close(void *opaque)
2996 QEMUFileSocket *s = opaque;
3001 static int popen_put_buffer(void *opaque, const uint8_t *buf, int64_t pos, int size)
3003 QEMUFilePopen *s = opaque;
3004 return fwrite(buf, 1, size, s->popen_file);
3007 static int popen_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)
3009 QEMUFilePopen *s = opaque;
3010 return fread(buf, 1, size, s->popen_file);
3013 static int popen_close(void *opaque)
3015 QEMUFilePopen *s = opaque;
3016 pclose(s->popen_file);
3021 QEMUFile *qemu_popen(FILE *popen_file, const char *mode)
3025 if (popen_file == NULL || mode == NULL || (mode[0] != 'r' && mode[0] != 'w') || mode[1] != 0) {
3026 fprintf(stderr, "qemu_popen: Argument validity check failed\n");
3030 s = qemu_mallocz(sizeof(QEMUFilePopen));
3032 fprintf(stderr, "qemu_popen: malloc failed\n");
3036 s->popen_file = popen_file;
3038 if(mode[0] == 'r') {
3039 s->file = qemu_fopen_ops(s, NULL, popen_get_buffer, popen_close, NULL);
3041 s->file = qemu_fopen_ops(s, popen_put_buffer, NULL, popen_close, NULL);
3043 fprintf(stderr, "qemu_popen: returning result of qemu_fopen_ops\n");
3047 QEMUFile *qemu_popen_cmd(const char *command, const char *mode)
3051 popen_file = popen(command, mode);
3052 if(popen_file == NULL) {
3056 return qemu_popen(popen_file, mode);
3059 QEMUFile *qemu_fopen_socket(int fd)
3061 QEMUFileSocket *s = qemu_mallocz(sizeof(QEMUFileSocket));
3067 s->file = qemu_fopen_ops(s, NULL, socket_get_buffer, socket_close, NULL);
3071 typedef struct QEMUFileStdio
3076 static int file_put_buffer(void *opaque, const uint8_t *buf,
3077 int64_t pos, int size)
3079 QEMUFileStdio *s = opaque;
3080 fseek(s->outfile, pos, SEEK_SET);
3081 fwrite(buf, 1, size, s->outfile);
3085 static int file_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)
3087 QEMUFileStdio *s = opaque;
3088 fseek(s->outfile, pos, SEEK_SET);
3089 return fread(buf, 1, size, s->outfile);
3092 static int file_close(void *opaque)
3094 QEMUFileStdio *s = opaque;
3100 QEMUFile *qemu_fopen(const char *filename, const char *mode)
3104 s = qemu_mallocz(sizeof(QEMUFileStdio));
3108 s->outfile = fopen(filename, mode);
3112 if (!strcmp(mode, "wb"))
3113 return qemu_fopen_ops(s, file_put_buffer, NULL, file_close, NULL);
3114 else if (!strcmp(mode, "rb"))
3115 return qemu_fopen_ops(s, NULL, file_get_buffer, file_close, NULL);
3124 typedef struct QEMUFileBdrv
3126 BlockDriverState *bs;
3127 int64_t base_offset;
3130 static int bdrv_put_buffer(void *opaque, const uint8_t *buf,
3131 int64_t pos, int size)
3133 QEMUFileBdrv *s = opaque;
3134 bdrv_pwrite(s->bs, s->base_offset + pos, buf, size);
3138 static int bdrv_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)
3140 QEMUFileBdrv *s = opaque;
3141 return bdrv_pread(s->bs, s->base_offset + pos, buf, size);
3144 static int bdrv_fclose(void *opaque)
3146 QEMUFileBdrv *s = opaque;
3151 static QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int64_t offset, int is_writable)
3155 s = qemu_mallocz(sizeof(QEMUFileBdrv));
3160 s->base_offset = offset;
3163 return qemu_fopen_ops(s, bdrv_put_buffer, NULL, bdrv_fclose, NULL);
3165 return qemu_fopen_ops(s, NULL, bdrv_get_buffer, bdrv_fclose, NULL);
3168 QEMUFile *qemu_fopen_ops(void *opaque, QEMUFilePutBufferFunc *put_buffer,
3169 QEMUFileGetBufferFunc *get_buffer,
3170 QEMUFileCloseFunc *close,
3171 QEMUFileRateLimit *rate_limit)
3175 f = qemu_mallocz(sizeof(QEMUFile));
3180 f->put_buffer = put_buffer;
3181 f->get_buffer = get_buffer;
3183 f->rate_limit = rate_limit;
3189 int qemu_file_has_error(QEMUFile *f)
3191 return f->has_error;
3194 void qemu_fflush(QEMUFile *f)
3199 if (f->is_write && f->buf_index > 0) {
3202 len = f->put_buffer(f->opaque, f->buf, f->buf_offset, f->buf_index);
3204 f->buf_offset += f->buf_index;
3211 static void qemu_fill_buffer(QEMUFile *f)
3221 len = f->get_buffer(f->opaque, f->buf, f->buf_offset, IO_BUF_SIZE);
3225 f->buf_offset += len;
3226 } else if (len != -EAGAIN)
3230 int qemu_fclose(QEMUFile *f)
3235 ret = f->close(f->opaque);
3240 void qemu_file_put_notify(QEMUFile *f)
3242 f->put_buffer(f->opaque, NULL, 0, 0);
3245 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
3249 if (!f->has_error && f->is_write == 0 && f->buf_index > 0) {
3251 "Attempted to write to buffer while read buffer is not empty\n");
3255 while (!f->has_error && size > 0) {
3256 l = IO_BUF_SIZE - f->buf_index;
3259 memcpy(f->buf + f->buf_index, buf, l);
3264 if (f->buf_index >= IO_BUF_SIZE)
3269 void qemu_put_byte(QEMUFile *f, int v)
3271 if (!f->has_error && f->is_write == 0 && f->buf_index > 0) {
3273 "Attempted to write to buffer while read buffer is not empty\n");
3277 f->buf[f->buf_index++] = v;
3279 if (f->buf_index >= IO_BUF_SIZE)
3283 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size1)
3292 l = f->buf_size - f->buf_index;
3294 qemu_fill_buffer(f);
3295 l = f->buf_size - f->buf_index;
3301 memcpy(buf, f->buf + f->buf_index, l);
3306 return size1 - size;
3309 int qemu_get_byte(QEMUFile *f)
3314 if (f->buf_index >= f->buf_size) {
3315 qemu_fill_buffer(f);
3316 if (f->buf_index >= f->buf_size)
3319 return f->buf[f->buf_index++];
3322 int64_t qemu_ftell(QEMUFile *f)
3324 return f->buf_offset - f->buf_size + f->buf_index;
3327 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
3329 if (whence == SEEK_SET) {
3331 } else if (whence == SEEK_CUR) {
3332 pos += qemu_ftell(f);
3334 /* SEEK_END not supported */
3337 if (f->put_buffer) {
3339 f->buf_offset = pos;
3341 f->buf_offset = pos;
3348 int qemu_file_rate_limit(QEMUFile *f)
3351 return f->rate_limit(f->opaque);
3356 void qemu_put_be16(QEMUFile *f, unsigned int v)
3358 qemu_put_byte(f, v >> 8);
3359 qemu_put_byte(f, v);
3362 void qemu_put_be32(QEMUFile *f, unsigned int v)
3364 qemu_put_byte(f, v >> 24);
3365 qemu_put_byte(f, v >> 16);
3366 qemu_put_byte(f, v >> 8);
3367 qemu_put_byte(f, v);
3370 void qemu_put_be64(QEMUFile *f, uint64_t v)
3372 qemu_put_be32(f, v >> 32);
3373 qemu_put_be32(f, v);
3376 unsigned int qemu_get_be16(QEMUFile *f)
3379 v = qemu_get_byte(f) << 8;
3380 v |= qemu_get_byte(f);
3384 unsigned int qemu_get_be32(QEMUFile *f)
3387 v = qemu_get_byte(f) << 24;
3388 v |= qemu_get_byte(f) << 16;
3389 v |= qemu_get_byte(f) << 8;
3390 v |= qemu_get_byte(f);
3394 uint64_t qemu_get_be64(QEMUFile *f)
3397 v = (uint64_t)qemu_get_be32(f) << 32;
3398 v |= qemu_get_be32(f);
3402 typedef struct SaveStateEntry {
3407 SaveLiveStateHandler *save_live_state;
3408 SaveStateHandler *save_state;
3409 LoadStateHandler *load_state;
3411 struct SaveStateEntry *next;
3414 static SaveStateEntry *first_se;
3416 /* TODO: Individual devices generally have very little idea about the rest
3417 of the system, so instance_id should be removed/replaced.
3418 Meanwhile pass -1 as instance_id if you do not already have a clearly
3419 distinguishing id for all instances of your device class. */
3420 int register_savevm_live(const char *idstr,
3423 SaveLiveStateHandler *save_live_state,
3424 SaveStateHandler *save_state,
3425 LoadStateHandler *load_state,
3428 SaveStateEntry *se, **pse;
3429 static int global_section_id;
3431 se = qemu_malloc(sizeof(SaveStateEntry));
3434 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
3435 se->instance_id = (instance_id == -1) ? 0 : instance_id;
3436 se->version_id = version_id;
3437 se->section_id = global_section_id++;
3438 se->save_live_state = save_live_state;
3439 se->save_state = save_state;
3440 se->load_state = load_state;
3441 se->opaque = opaque;
3444 /* add at the end of list */
3446 while (*pse != NULL) {
3447 if (instance_id == -1
3448 && strcmp(se->idstr, (*pse)->idstr) == 0
3449 && se->instance_id <= (*pse)->instance_id)
3450 se->instance_id = (*pse)->instance_id + 1;
3451 pse = &(*pse)->next;
3457 int register_savevm(const char *idstr,
3460 SaveStateHandler *save_state,
3461 LoadStateHandler *load_state,
3464 return register_savevm_live(idstr, instance_id, version_id,
3465 NULL, save_state, load_state, opaque);
3468 #define QEMU_VM_FILE_MAGIC 0x5145564d
3469 #define QEMU_VM_FILE_VERSION_COMPAT 0x00000002
3470 #define QEMU_VM_FILE_VERSION 0x00000003
3472 #define QEMU_VM_EOF 0x00
3473 #define QEMU_VM_SECTION_START 0x01
3474 #define QEMU_VM_SECTION_PART 0x02
3475 #define QEMU_VM_SECTION_END 0x03
3476 #define QEMU_VM_SECTION_FULL 0x04
3478 int qemu_savevm_state_begin(QEMUFile *f)
3482 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
3483 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
3485 for (se = first_se; se != NULL; se = se->next) {
3488 if (se->save_live_state == NULL)
3492 qemu_put_byte(f, QEMU_VM_SECTION_START);
3493 qemu_put_be32(f, se->section_id);
3496 len = strlen(se->idstr);
3497 qemu_put_byte(f, len);
3498 qemu_put_buffer(f, (uint8_t *)se->idstr, len);
3500 qemu_put_be32(f, se->instance_id);
3501 qemu_put_be32(f, se->version_id);
3503 se->save_live_state(f, QEMU_VM_SECTION_START, se->opaque);
3506 if (qemu_file_has_error(f))
3512 int qemu_savevm_state_iterate(QEMUFile *f)
3517 for (se = first_se; se != NULL; se = se->next) {
3518 if (se->save_live_state == NULL)
3522 qemu_put_byte(f, QEMU_VM_SECTION_PART);
3523 qemu_put_be32(f, se->section_id);
3525 ret &= !!se->save_live_state(f, QEMU_VM_SECTION_PART, se->opaque);
3531 if (qemu_file_has_error(f))
3537 int qemu_savevm_state_complete(QEMUFile *f)
3541 for (se = first_se; se != NULL; se = se->next) {
3542 if (se->save_live_state == NULL)
3546 qemu_put_byte(f, QEMU_VM_SECTION_END);
3547 qemu_put_be32(f, se->section_id);
3549 se->save_live_state(f, QEMU_VM_SECTION_END, se->opaque);
3552 for(se = first_se; se != NULL; se = se->next) {
3555 if (se->save_state == NULL)
3559 qemu_put_byte(f, QEMU_VM_SECTION_FULL);
3560 qemu_put_be32(f, se->section_id);
3563 len = strlen(se->idstr);
3564 qemu_put_byte(f, len);
3565 qemu_put_buffer(f, (uint8_t *)se->idstr, len);
3567 qemu_put_be32(f, se->instance_id);
3568 qemu_put_be32(f, se->version_id);
3570 se->save_state(f, se->opaque);
3573 qemu_put_byte(f, QEMU_VM_EOF);
3575 if (qemu_file_has_error(f))
3581 int qemu_savevm_state(QEMUFile *f)
3583 int saved_vm_running;
3586 saved_vm_running = vm_running;
3591 ret = qemu_savevm_state_begin(f);
3596 ret = qemu_savevm_state_iterate(f);
3601 ret = qemu_savevm_state_complete(f);
3604 if (qemu_file_has_error(f))
3607 if (!ret && saved_vm_running)
3613 static SaveStateEntry *find_se(const char *idstr, int instance_id)
3617 for(se = first_se; se != NULL; se = se->next) {
3618 if (!strcmp(se->idstr, idstr) &&
3619 instance_id == se->instance_id)
3625 typedef struct LoadStateEntry {
3629 struct LoadStateEntry *next;
3632 static int qemu_loadvm_state_v2(QEMUFile *f)
3635 int len, ret, instance_id, record_len, version_id;
3636 int64_t total_len, end_pos, cur_pos;
3639 total_len = qemu_get_be64(f);
3640 end_pos = total_len + qemu_ftell(f);
3642 if (qemu_ftell(f) >= end_pos)
3644 len = qemu_get_byte(f);
3645 qemu_get_buffer(f, (uint8_t *)idstr, len);
3647 instance_id = qemu_get_be32(f);
3648 version_id = qemu_get_be32(f);
3649 record_len = qemu_get_be32(f);
3650 cur_pos = qemu_ftell(f);
3651 se = find_se(idstr, instance_id);
3653 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
3654 instance_id, idstr);
3656 ret = se->load_state(f, se->opaque, version_id);
3658 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
3659 instance_id, idstr);
3662 /* always seek to exact end of record */
3663 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
3666 if (qemu_file_has_error(f))
3672 int qemu_loadvm_state(QEMUFile *f)
3674 LoadStateEntry *first_le = NULL;
3675 uint8_t section_type;
3679 v = qemu_get_be32(f);
3680 if (v != QEMU_VM_FILE_MAGIC)
3683 v = qemu_get_be32(f);
3684 if (v == QEMU_VM_FILE_VERSION_COMPAT)
3685 return qemu_loadvm_state_v2(f);
3686 if (v != QEMU_VM_FILE_VERSION)
3689 while ((section_type = qemu_get_byte(f)) != QEMU_VM_EOF) {
3690 uint32_t instance_id, version_id, section_id;
3696 switch (section_type) {
3697 case QEMU_VM_SECTION_START:
3698 case QEMU_VM_SECTION_FULL:
3699 /* Read section start */
3700 section_id = qemu_get_be32(f);
3701 len = qemu_get_byte(f);
3702 qemu_get_buffer(f, (uint8_t *)idstr, len);
3704 instance_id = qemu_get_be32(f);
3705 version_id = qemu_get_be32(f);
3707 /* Find savevm section */
3708 se = find_se(idstr, instance_id);
3710 fprintf(stderr, "Unknown savevm section or instance '%s' %d\n", idstr, instance_id);
3715 /* Validate version */
3716 if (version_id > se->version_id) {
3717 fprintf(stderr, "savevm: unsupported version %d for '%s' v%d\n",
3718 version_id, idstr, se->version_id);
3724 le = qemu_mallocz(sizeof(*le));
3731 le->section_id = section_id;
3732 le->version_id = version_id;
3733 le->next = first_le;
3736 le->se->load_state(f, le->se->opaque, le->version_id);
3738 case QEMU_VM_SECTION_PART:
3739 case QEMU_VM_SECTION_END:
3740 section_id = qemu_get_be32(f);
3742 for (le = first_le; le && le->section_id != section_id; le = le->next);
3744 fprintf(stderr, "Unknown savevm section %d\n", section_id);
3749 le->se->load_state(f, le->se->opaque, le->version_id);
3752 fprintf(stderr, "Unknown savevm section type %d\n", section_type);
3762 LoadStateEntry *le = first_le;
3763 first_le = first_le->next;
3767 if (qemu_file_has_error(f))
3773 /* device can contain snapshots */
3774 static int bdrv_can_snapshot(BlockDriverState *bs)
3777 !bdrv_is_removable(bs) &&
3778 !bdrv_is_read_only(bs));
3781 /* device must be snapshots in order to have a reliable snapshot */
3782 static int bdrv_has_snapshot(BlockDriverState *bs)
3785 !bdrv_is_removable(bs) &&
3786 !bdrv_is_read_only(bs));
3789 static BlockDriverState *get_bs_snapshots(void)
3791 BlockDriverState *bs;
3795 return bs_snapshots;
3796 for(i = 0; i <= nb_drives; i++) {
3797 bs = drives_table[i].bdrv;
3798 if (bdrv_can_snapshot(bs))
3807 static int bdrv_snapshot_find(BlockDriverState *bs, QEMUSnapshotInfo *sn_info,
3810 QEMUSnapshotInfo *sn_tab, *sn;
3814 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
3817 for(i = 0; i < nb_sns; i++) {
3819 if (!strcmp(sn->id_str, name) || !strcmp(sn->name, name)) {
3829 void do_savevm(const char *name)
3831 BlockDriverState *bs, *bs1;
3832 QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
3833 int must_delete, ret, i;
3834 BlockDriverInfo bdi1, *bdi = &bdi1;
3836 int saved_vm_running;
3843 bs = get_bs_snapshots();
3845 term_printf("No block device can accept snapshots\n");
3849 /* ??? Should this occur after vm_stop? */
3852 saved_vm_running = vm_running;
3857 ret = bdrv_snapshot_find(bs, old_sn, name);
3862 memset(sn, 0, sizeof(*sn));
3864 pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
3865 pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
3868 pstrcpy(sn->name, sizeof(sn->name), name);
3871 /* fill auxiliary fields */
3874 sn->date_sec = tb.time;
3875 sn->date_nsec = tb.millitm * 1000000;
3877 gettimeofday(&tv, NULL);
3878 sn->date_sec = tv.tv_sec;
3879 sn->date_nsec = tv.tv_usec * 1000;
3881 sn->vm_clock_nsec = qemu_get_clock(vm_clock);
3883 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
3884 term_printf("Device %s does not support VM state snapshots\n",
3885 bdrv_get_device_name(bs));
3889 /* save the VM state */
3890 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 1);
3892 term_printf("Could not open VM state file\n");
3895 ret = qemu_savevm_state(f);
3896 sn->vm_state_size = qemu_ftell(f);
3899 term_printf("Error %d while writing VM\n", ret);
3903 /* create the snapshots */
3905 for(i = 0; i < nb_drives; i++) {
3906 bs1 = drives_table[i].bdrv;
3907 if (bdrv_has_snapshot(bs1)) {
3909 ret = bdrv_snapshot_delete(bs1, old_sn->id_str);
3911 term_printf("Error while deleting snapshot on '%s'\n",
3912 bdrv_get_device_name(bs1));
3915 ret = bdrv_snapshot_create(bs1, sn);
3917 term_printf("Error while creating snapshot on '%s'\n",
3918 bdrv_get_device_name(bs1));
3924 if (saved_vm_running)
3928 void do_loadvm(const char *name)
3930 BlockDriverState *bs, *bs1;
3931 BlockDriverInfo bdi1, *bdi = &bdi1;
3934 int saved_vm_running;
3936 bs = get_bs_snapshots();
3938 term_printf("No block device supports snapshots\n");
3942 /* Flush all IO requests so they don't interfere with the new state. */
3945 saved_vm_running = vm_running;
3948 for(i = 0; i <= nb_drives; i++) {
3949 bs1 = drives_table[i].bdrv;
3950 if (bdrv_has_snapshot(bs1)) {
3951 ret = bdrv_snapshot_goto(bs1, name);
3954 term_printf("Warning: ");
3957 term_printf("Snapshots not supported on device '%s'\n",
3958 bdrv_get_device_name(bs1));
3961 term_printf("Could not find snapshot '%s' on device '%s'\n",
3962 name, bdrv_get_device_name(bs1));
3965 term_printf("Error %d while activating snapshot on '%s'\n",
3966 ret, bdrv_get_device_name(bs1));
3969 /* fatal on snapshot block device */
3976 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
3977 term_printf("Device %s does not support VM state snapshots\n",
3978 bdrv_get_device_name(bs));
3982 /* restore the VM state */
3983 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 0);
3985 term_printf("Could not open VM state file\n");
3988 ret = qemu_loadvm_state(f);
3991 term_printf("Error %d while loading VM state\n", ret);
3994 if (saved_vm_running)
3998 void do_delvm(const char *name)
4000 BlockDriverState *bs, *bs1;
4003 bs = get_bs_snapshots();
4005 term_printf("No block device supports snapshots\n");
4009 for(i = 0; i <= nb_drives; i++) {
4010 bs1 = drives_table[i].bdrv;
4011 if (bdrv_has_snapshot(bs1)) {
4012 ret = bdrv_snapshot_delete(bs1, name);
4014 if (ret == -ENOTSUP)
4015 term_printf("Snapshots not supported on device '%s'\n",
4016 bdrv_get_device_name(bs1));
4018 term_printf("Error %d while deleting snapshot on '%s'\n",
4019 ret, bdrv_get_device_name(bs1));
4025 void do_info_snapshots(void)
4027 BlockDriverState *bs, *bs1;
4028 QEMUSnapshotInfo *sn_tab, *sn;
4032 bs = get_bs_snapshots();
4034 term_printf("No available block device supports snapshots\n");
4037 term_printf("Snapshot devices:");
4038 for(i = 0; i <= nb_drives; i++) {
4039 bs1 = drives_table[i].bdrv;
4040 if (bdrv_has_snapshot(bs1)) {
4042 term_printf(" %s", bdrv_get_device_name(bs1));
4047 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
4049 term_printf("bdrv_snapshot_list: error %d\n", nb_sns);
4052 term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs));
4053 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
4054 for(i = 0; i < nb_sns; i++) {
4056 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
4061 /***********************************************************/
4062 /* ram save/restore */
4064 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
4068 v = qemu_get_byte(f);
4071 if (qemu_get_buffer(f, buf, len) != len)
4075 v = qemu_get_byte(f);
4076 memset(buf, v, len);
4082 if (qemu_file_has_error(f))
4088 static int ram_load_v1(QEMUFile *f, void *opaque)
4093 if (qemu_get_be32(f) != phys_ram_size)
4095 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
4096 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
4103 #define BDRV_HASH_BLOCK_SIZE 1024
4104 #define IOBUF_SIZE 4096
4105 #define RAM_CBLOCK_MAGIC 0xfabe
4107 typedef struct RamDecompressState {
4110 uint8_t buf[IOBUF_SIZE];
4111 } RamDecompressState;
4113 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
4116 memset(s, 0, sizeof(*s));
4118 ret = inflateInit(&s->zstream);
4124 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
4128 s->zstream.avail_out = len;
4129 s->zstream.next_out = buf;
4130 while (s->zstream.avail_out > 0) {
4131 if (s->zstream.avail_in == 0) {
4132 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
4134 clen = qemu_get_be16(s->f);
4135 if (clen > IOBUF_SIZE)
4137 qemu_get_buffer(s->f, s->buf, clen);
4138 s->zstream.avail_in = clen;
4139 s->zstream.next_in = s->buf;
4141 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
4142 if (ret != Z_OK && ret != Z_STREAM_END) {
4149 static void ram_decompress_close(RamDecompressState *s)
4151 inflateEnd(&s->zstream);
4154 #define RAM_SAVE_FLAG_FULL 0x01
4155 #define RAM_SAVE_FLAG_COMPRESS 0x02
4156 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
4157 #define RAM_SAVE_FLAG_PAGE 0x08
4158 #define RAM_SAVE_FLAG_EOS 0x10
4160 static int is_dup_page(uint8_t *page, uint8_t ch)
4162 uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
4163 uint32_t *array = (uint32_t *)page;
4166 for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
4167 if (array[i] != val)
4174 static int ram_save_block(QEMUFile *f)
4176 static ram_addr_t current_addr = 0;
4177 ram_addr_t saved_addr = current_addr;
4178 ram_addr_t addr = 0;
4181 while (addr < phys_ram_size) {
4182 if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
4185 cpu_physical_memory_reset_dirty(current_addr,
4186 current_addr + TARGET_PAGE_SIZE,
4187 MIGRATION_DIRTY_FLAG);
4189 ch = *(phys_ram_base + current_addr);
4191 if (is_dup_page(phys_ram_base + current_addr, ch)) {
4192 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
4193 qemu_put_byte(f, ch);
4195 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
4196 qemu_put_buffer(f, phys_ram_base + current_addr, TARGET_PAGE_SIZE);
4202 addr += TARGET_PAGE_SIZE;
4203 current_addr = (saved_addr + addr) % phys_ram_size;
4209 static ram_addr_t ram_save_threshold = 10;
4211 static ram_addr_t ram_save_remaining(void)
4214 ram_addr_t count = 0;
4216 for (addr = 0; addr < phys_ram_size; addr += TARGET_PAGE_SIZE) {
4217 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
4224 static int ram_save_live(QEMUFile *f, int stage, void *opaque)
4229 /* Make sure all dirty bits are set */
4230 for (addr = 0; addr < phys_ram_size; addr += TARGET_PAGE_SIZE) {
4231 if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
4232 cpu_physical_memory_set_dirty(addr);
4235 /* Enable dirty memory tracking */
4236 cpu_physical_memory_set_dirty_tracking(1);
4238 qemu_put_be64(f, phys_ram_size | RAM_SAVE_FLAG_MEM_SIZE);
4241 while (!qemu_file_rate_limit(f)) {
4244 ret = ram_save_block(f);
4245 if (ret == 0) /* no more blocks */
4249 /* try transferring iterative blocks of memory */
4252 cpu_physical_memory_set_dirty_tracking(0);
4254 /* flush all remaining blocks regardless of rate limiting */
4255 while (ram_save_block(f) != 0);
4258 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
4260 return (stage == 2) && (ram_save_remaining() < ram_save_threshold);
4263 static int ram_load_dead(QEMUFile *f, void *opaque)
4265 RamDecompressState s1, *s = &s1;
4269 if (ram_decompress_open(s, f) < 0)
4271 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
4272 if (ram_decompress_buf(s, buf, 1) < 0) {
4273 fprintf(stderr, "Error while reading ram block header\n");
4277 if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
4278 fprintf(stderr, "Error while reading ram block address=0x%08" PRIx64, (uint64_t)i);
4283 printf("Error block header\n");
4287 ram_decompress_close(s);
4292 static int ram_load(QEMUFile *f, void *opaque, int version_id)
4297 if (version_id == 1)
4298 return ram_load_v1(f, opaque);
4300 if (version_id == 2) {
4301 if (qemu_get_be32(f) != phys_ram_size)
4303 return ram_load_dead(f, opaque);
4306 if (version_id != 3)
4310 addr = qemu_get_be64(f);
4312 flags = addr & ~TARGET_PAGE_MASK;
4313 addr &= TARGET_PAGE_MASK;
4315 if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
4316 if (addr != phys_ram_size)
4320 if (flags & RAM_SAVE_FLAG_FULL) {
4321 if (ram_load_dead(f, opaque) < 0)
4325 if (flags & RAM_SAVE_FLAG_COMPRESS) {
4326 uint8_t ch = qemu_get_byte(f);
4327 memset(phys_ram_base + addr, ch, TARGET_PAGE_SIZE);
4328 } else if (flags & RAM_SAVE_FLAG_PAGE)
4329 qemu_get_buffer(f, phys_ram_base + addr, TARGET_PAGE_SIZE);
4330 } while (!(flags & RAM_SAVE_FLAG_EOS));
4335 void qemu_service_io(void)
4337 CPUState *env = cpu_single_env;
4339 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
4341 if (env->kqemu_enabled) {
4342 kqemu_cpu_interrupt(env);
4348 /***********************************************************/
4349 /* bottom halves (can be seen as timers which expire ASAP) */
4360 static QEMUBH *first_bh = NULL;
4362 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
4365 bh = qemu_mallocz(sizeof(QEMUBH));
4369 bh->opaque = opaque;
4370 bh->next = first_bh;
4375 int qemu_bh_poll(void)
4381 for (bh = first_bh; bh; bh = bh->next) {
4382 if (!bh->deleted && bh->scheduled) {
4391 /* remove deleted bhs */
4405 void qemu_bh_schedule_idle(QEMUBH *bh)
4413 void qemu_bh_schedule(QEMUBH *bh)
4415 CPUState *env = cpu_single_env;
4420 /* stop the currently executing CPU to execute the BH ASAP */
4422 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
4426 void qemu_bh_cancel(QEMUBH *bh)
4431 void qemu_bh_delete(QEMUBH *bh)
4437 static void qemu_bh_update_timeout(int *timeout)
4441 for (bh = first_bh; bh; bh = bh->next) {
4442 if (!bh->deleted && bh->scheduled) {
4444 /* idle bottom halves will be polled at least
4446 *timeout = MIN(10, *timeout);
4448 /* non-idle bottom halves will be executed
4457 /***********************************************************/
4458 /* machine registration */
4460 static QEMUMachine *first_machine = NULL;
4462 int qemu_register_machine(QEMUMachine *m)
4465 pm = &first_machine;
4473 static QEMUMachine *find_machine(const char *name)
4477 for(m = first_machine; m != NULL; m = m->next) {
4478 if (!strcmp(m->name, name))
4484 /***********************************************************/
4485 /* main execution loop */
4487 static void gui_update(void *opaque)
4489 DisplayState *ds = opaque;
4490 ds->dpy_refresh(ds);
4491 qemu_mod_timer(ds->gui_timer,
4492 (ds->gui_timer_interval ?
4493 ds->gui_timer_interval :
4494 GUI_REFRESH_INTERVAL)
4495 + qemu_get_clock(rt_clock));
4498 struct vm_change_state_entry {
4499 VMChangeStateHandler *cb;
4501 LIST_ENTRY (vm_change_state_entry) entries;
4504 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
4506 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
4509 VMChangeStateEntry *e;
4511 e = qemu_mallocz(sizeof (*e));
4517 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
4521 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
4523 LIST_REMOVE (e, entries);
4527 static void vm_state_notify(int running)
4529 VMChangeStateEntry *e;
4531 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
4532 e->cb(e->opaque, running);
4536 /* XXX: support several handlers */
4537 static VMStopHandler *vm_stop_cb;
4538 static void *vm_stop_opaque;
4540 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
4543 vm_stop_opaque = opaque;
4547 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
4558 qemu_rearm_alarm_timer(alarm_timer);
4562 void vm_stop(int reason)
4565 cpu_disable_ticks();
4569 vm_stop_cb(vm_stop_opaque, reason);
4576 /* reset/shutdown handler */
4578 typedef struct QEMUResetEntry {
4579 QEMUResetHandler *func;
4581 struct QEMUResetEntry *next;
4584 static QEMUResetEntry *first_reset_entry;
4585 static int reset_requested;
4586 static int shutdown_requested;
4587 static int powerdown_requested;
4589 int qemu_shutdown_requested(void)
4591 int r = shutdown_requested;
4592 shutdown_requested = 0;
4596 int qemu_reset_requested(void)
4598 int r = reset_requested;
4599 reset_requested = 0;
4603 int qemu_powerdown_requested(void)
4605 int r = powerdown_requested;
4606 powerdown_requested = 0;
4610 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
4612 QEMUResetEntry **pre, *re;
4614 pre = &first_reset_entry;
4615 while (*pre != NULL)
4616 pre = &(*pre)->next;
4617 re = qemu_mallocz(sizeof(QEMUResetEntry));
4619 re->opaque = opaque;
4624 void qemu_system_reset(void)
4628 /* reset all devices */
4629 for(re = first_reset_entry; re != NULL; re = re->next) {
4630 re->func(re->opaque);
4634 void qemu_system_reset_request(void)
4637 shutdown_requested = 1;
4639 reset_requested = 1;
4642 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
4645 void qemu_system_shutdown_request(void)
4647 shutdown_requested = 1;
4649 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
4652 void qemu_system_powerdown_request(void)
4654 powerdown_requested = 1;
4656 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
4660 void host_main_loop_wait(int *timeout)
4666 /* XXX: need to suppress polling by better using win32 events */
4668 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
4669 ret |= pe->func(pe->opaque);
4673 WaitObjects *w = &wait_objects;
4675 ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
4676 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
4677 if (w->func[ret - WAIT_OBJECT_0])
4678 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
4680 /* Check for additional signaled events */
4681 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
4683 /* Check if event is signaled */
4684 ret2 = WaitForSingleObject(w->events[i], 0);
4685 if(ret2 == WAIT_OBJECT_0) {
4687 w->func[i](w->opaque[i]);
4688 } else if (ret2 == WAIT_TIMEOUT) {
4690 err = GetLastError();
4691 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
4694 } else if (ret == WAIT_TIMEOUT) {
4696 err = GetLastError();
4697 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
4704 void host_main_loop_wait(int *timeout)
4709 void main_loop_wait(int timeout)
4711 IOHandlerRecord *ioh;
4712 fd_set rfds, wfds, xfds;
4716 qemu_bh_update_timeout(&timeout);
4718 host_main_loop_wait(&timeout);
4720 /* poll any events */
4721 /* XXX: separate device handlers from system ones */
4726 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4730 (!ioh->fd_read_poll ||
4731 ioh->fd_read_poll(ioh->opaque) != 0)) {
4732 FD_SET(ioh->fd, &rfds);
4736 if (ioh->fd_write) {
4737 FD_SET(ioh->fd, &wfds);
4743 tv.tv_sec = timeout / 1000;
4744 tv.tv_usec = (timeout % 1000) * 1000;
4746 #if defined(CONFIG_SLIRP)
4747 if (slirp_is_inited()) {
4748 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
4751 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
4753 IOHandlerRecord **pioh;
4755 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4756 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
4757 ioh->fd_read(ioh->opaque);
4759 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
4760 ioh->fd_write(ioh->opaque);
4764 /* remove deleted IO handlers */
4765 pioh = &first_io_handler;
4775 #if defined(CONFIG_SLIRP)
4776 if (slirp_is_inited()) {
4782 slirp_select_poll(&rfds, &wfds, &xfds);
4786 /* Check bottom-halves last in case any of the earlier events triggered
4792 static int main_loop(void)
4795 #ifdef CONFIG_PROFILER
4800 cur_cpu = first_cpu;
4801 next_cpu = cur_cpu->next_cpu ?: first_cpu;
4808 #ifdef CONFIG_PROFILER
4809 ti = profile_getclock();
4814 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
4815 env->icount_decr.u16.low = 0;
4816 env->icount_extra = 0;
4817 count = qemu_next_deadline();
4818 count = (count + (1 << icount_time_shift) - 1)
4819 >> icount_time_shift;
4820 qemu_icount += count;
4821 decr = (count > 0xffff) ? 0xffff : count;
4823 env->icount_decr.u16.low = decr;
4824 env->icount_extra = count;
4826 ret = cpu_exec(env);
4827 #ifdef CONFIG_PROFILER
4828 qemu_time += profile_getclock() - ti;
4831 /* Fold pending instructions back into the
4832 instruction counter, and clear the interrupt flag. */
4833 qemu_icount -= (env->icount_decr.u16.low
4834 + env->icount_extra);
4835 env->icount_decr.u32 = 0;
4836 env->icount_extra = 0;
4838 next_cpu = env->next_cpu ?: first_cpu;
4839 if (event_pending && likely(ret != EXCP_DEBUG)) {
4840 ret = EXCP_INTERRUPT;
4844 if (ret == EXCP_HLT) {
4845 /* Give the next CPU a chance to run. */
4849 if (ret != EXCP_HALTED)
4851 /* all CPUs are halted ? */
4857 if (shutdown_requested) {
4858 ret = EXCP_INTERRUPT;
4866 if (reset_requested) {
4867 reset_requested = 0;
4868 qemu_system_reset();
4869 ret = EXCP_INTERRUPT;
4871 if (powerdown_requested) {
4872 powerdown_requested = 0;
4873 qemu_system_powerdown();
4874 ret = EXCP_INTERRUPT;
4876 if (unlikely(ret == EXCP_DEBUG)) {
4877 vm_stop(EXCP_DEBUG);
4879 /* If all cpus are halted then wait until the next IRQ */
4880 /* XXX: use timeout computed from timers */
4881 if (ret == EXCP_HALTED) {
4885 /* Advance virtual time to the next event. */
4886 if (use_icount == 1) {
4887 /* When not using an adaptive execution frequency
4888 we tend to get badly out of sync with real time,
4889 so just delay for a reasonable amount of time. */
4892 delta = cpu_get_icount() - cpu_get_clock();
4895 /* If virtual time is ahead of real time then just
4897 timeout = (delta / 1000000) + 1;
4899 /* Wait for either IO to occur or the next
4901 add = qemu_next_deadline();
4902 /* We advance the timer before checking for IO.
4903 Limit the amount we advance so that early IO
4904 activity won't get the guest too far ahead. */
4908 add = (add + (1 << icount_time_shift) - 1)
4909 >> icount_time_shift;
4911 timeout = delta / 1000000;
4922 if (shutdown_requested) {
4923 ret = EXCP_INTERRUPT;
4928 #ifdef CONFIG_PROFILER
4929 ti = profile_getclock();
4931 main_loop_wait(timeout);
4932 #ifdef CONFIG_PROFILER
4933 dev_time += profile_getclock() - ti;
4936 cpu_disable_ticks();
4940 static void help(int exitcode)
4942 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n"
4943 "usage: %s [options] [disk_image]\n"
4945 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4947 "Standard options:\n"
4948 "-M machine select emulated machine (-M ? for list)\n"
4949 "-cpu cpu select CPU (-cpu ? for list)\n"
4950 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
4951 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
4952 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
4953 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
4954 "-drive [file=file][,if=type][,bus=n][,unit=m][,media=d][,index=i]\n"
4955 " [,cyls=c,heads=h,secs=s[,trans=t]][,snapshot=on|off]\n"
4956 " [,cache=writethrough|writeback|none][,format=f]\n"
4957 " use 'file' as a drive image\n"
4958 "-mtdblock file use 'file' as on-board Flash memory image\n"
4959 "-sd file use 'file' as SecureDigital card image\n"
4960 "-pflash file use 'file' as a parallel flash image\n"
4961 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
4962 "-snapshot write to temporary files instead of disk image files\n"
4964 "-no-frame open SDL window without a frame and window decorations\n"
4965 "-alt-grab use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
4966 "-no-quit disable SDL window close capability\n"
4969 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
4971 "-m megs set virtual RAM size to megs MB [default=%d]\n"
4972 "-smp n set the number of CPUs to 'n' [default=1]\n"
4973 "-nographic disable graphical output and redirect serial I/Os to console\n"
4974 "-portrait rotate graphical output 90 deg left (only PXA LCD)\n"
4976 "-k language use keyboard layout (for example \"fr\" for French)\n"
4979 "-audio-help print list of audio drivers and their options\n"
4980 "-soundhw c1,... enable audio support\n"
4981 " and only specified sound cards (comma separated list)\n"
4982 " use -soundhw ? to get the list of supported cards\n"
4983 " use -soundhw all to enable all of them\n"
4985 "-vga [std|cirrus|vmware]\n"
4986 " select video card type\n"
4987 "-localtime set the real time clock to local time [default=utc]\n"
4988 "-full-screen start in full screen\n"
4990 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
4992 "-usb enable the USB driver (will be the default soon)\n"
4993 "-usbdevice name add the host or guest USB device 'name'\n"
4994 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
4995 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
4997 "-name string set the name of the guest\n"
4998 "-uuid %%08x-%%04x-%%04x-%%04x-%%012x specify machine UUID\n"
5000 "Network options:\n"
5001 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
5002 " create a new Network Interface Card and connect it to VLAN 'n'\n"
5004 "-net user[,vlan=n][,hostname=host]\n"
5005 " connect the user mode network stack to VLAN 'n' and send\n"
5006 " hostname 'host' to DHCP clients\n"
5009 "-net tap[,vlan=n],ifname=name\n"
5010 " connect the host TAP network interface to VLAN 'n'\n"
5012 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file][,downscript=dfile]\n"
5013 " connect the host TAP network interface to VLAN 'n' and use the\n"
5014 " network scripts 'file' (default=%s)\n"
5015 " and 'dfile' (default=%s);\n"
5016 " use '[down]script=no' to disable script execution;\n"
5017 " use 'fd=h' to connect to an already opened TAP interface\n"
5019 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
5020 " connect the vlan 'n' to another VLAN using a socket connection\n"
5021 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
5022 " connect the vlan 'n' to multicast maddr and port\n"
5024 "-net vde[,vlan=n][,sock=socketpath][,port=n][,group=groupname][,mode=octalmode]\n"
5025 " connect the vlan 'n' to port 'n' of a vde switch running\n"
5026 " on host and listening for incoming connections on 'socketpath'.\n"
5027 " Use group 'groupname' and mode 'octalmode' to change default\n"
5028 " ownership and permissions for communication port.\n"
5030 "-net none use it alone to have zero network devices; if no -net option\n"
5031 " is provided, the default is '-net nic -net user'\n"
5033 "-bt hci,null Dumb bluetooth HCI - doesn't respond to commands\n"
5034 "-bt hci,host[:id]\n"
5035 " Use host's HCI with the given name\n"
5036 "-bt hci[,vlan=n]\n"
5037 " Emulate a standard HCI in virtual scatternet 'n'\n"
5038 "-bt vhci[,vlan=n]\n"
5039 " Add host computer to virtual scatternet 'n' using VHCI\n"
5040 "-bt device:dev[,vlan=n]\n"
5041 " Emulate a bluetooth device 'dev' in scatternet 'n'\n"
5044 "-tftp dir allow tftp access to files in dir [-net user]\n"
5045 "-bootp file advertise file in BOOTP replies\n"
5047 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
5049 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
5050 " redirect TCP or UDP connections from host to guest [-net user]\n"
5053 "Linux boot specific:\n"
5054 "-kernel bzImage use 'bzImage' as kernel image\n"
5055 "-append cmdline use 'cmdline' as kernel command line\n"
5056 "-initrd file use 'file' as initial ram disk\n"
5058 "Debug/Expert options:\n"
5059 "-monitor dev redirect the monitor to char device 'dev'\n"
5060 "-serial dev redirect the serial port to char device 'dev'\n"
5061 "-parallel dev redirect the parallel port to char device 'dev'\n"
5062 "-pidfile file Write PID to 'file'\n"
5063 "-S freeze CPU at startup (use 'c' to start execution)\n"
5064 "-s wait gdb connection to port\n"
5065 "-p port set gdb connection port [default=%s]\n"
5066 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
5067 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
5068 " translation (t=none or lba) (usually qemu can guess them)\n"
5069 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
5071 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
5072 "-no-kqemu disable KQEMU kernel module usage\n"
5075 "-enable-kvm enable KVM full virtualization support\n"
5078 "-no-acpi disable ACPI\n"
5080 #ifdef CONFIG_CURSES
5081 "-curses use a curses/ncurses interface instead of SDL\n"
5083 "-no-reboot exit instead of rebooting\n"
5084 "-no-shutdown stop before shutdown\n"
5085 "-loadvm [tag|id] start right away with a saved state (loadvm in monitor)\n"
5086 "-vnc display start a VNC server on display\n"
5088 "-daemonize daemonize QEMU after initializing\n"
5090 "-option-rom rom load a file, rom, into the option ROM space\n"
5092 "-prom-env variable=value set OpenBIOS nvram variables\n"
5094 "-clock force the use of the given methods for timer alarm.\n"
5095 " To see what timers are available use -clock ?\n"
5096 "-startdate select initial date of the clock\n"
5097 "-icount [N|auto]\n"
5098 " Enable virtual instruction counter with 2^N clock ticks per instruction\n"
5100 "During emulation, the following keys are useful:\n"
5101 "ctrl-alt-f toggle full screen\n"
5102 "ctrl-alt-n switch to virtual console 'n'\n"
5103 "ctrl-alt toggle mouse and keyboard grab\n"
5105 "When using -nographic, press 'ctrl-a h' to get some help.\n"
5110 DEFAULT_NETWORK_SCRIPT,
5111 DEFAULT_NETWORK_DOWN_SCRIPT,
5113 DEFAULT_GDBSTUB_PORT,
5118 #define HAS_ARG 0x0001
5133 QEMU_OPTION_mtdblock,
5137 QEMU_OPTION_snapshot,
5139 QEMU_OPTION_no_fd_bootchk,
5142 QEMU_OPTION_nographic,
5143 QEMU_OPTION_portrait,
5145 QEMU_OPTION_audio_help,
5146 QEMU_OPTION_soundhw,
5168 QEMU_OPTION_localtime,
5172 QEMU_OPTION_monitor,
5174 QEMU_OPTION_parallel,
5176 QEMU_OPTION_full_screen,
5177 QEMU_OPTION_no_frame,
5178 QEMU_OPTION_alt_grab,
5179 QEMU_OPTION_no_quit,
5180 QEMU_OPTION_pidfile,
5181 QEMU_OPTION_no_kqemu,
5182 QEMU_OPTION_kernel_kqemu,
5183 QEMU_OPTION_enable_kvm,
5184 QEMU_OPTION_win2k_hack,
5186 QEMU_OPTION_usbdevice,
5189 QEMU_OPTION_no_acpi,
5191 QEMU_OPTION_no_reboot,
5192 QEMU_OPTION_no_shutdown,
5193 QEMU_OPTION_show_cursor,
5194 QEMU_OPTION_daemonize,
5195 QEMU_OPTION_option_rom,
5196 QEMU_OPTION_semihosting,
5198 QEMU_OPTION_prom_env,
5199 QEMU_OPTION_old_param,
5201 QEMU_OPTION_startdate,
5202 QEMU_OPTION_tb_size,
5205 QEMU_OPTION_incoming,
5208 typedef struct QEMUOption {
5214 static const QEMUOption qemu_options[] = {
5215 { "h", 0, QEMU_OPTION_h },
5216 { "help", 0, QEMU_OPTION_h },
5218 { "M", HAS_ARG, QEMU_OPTION_M },
5219 { "cpu", HAS_ARG, QEMU_OPTION_cpu },
5220 { "fda", HAS_ARG, QEMU_OPTION_fda },
5221 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
5222 { "hda", HAS_ARG, QEMU_OPTION_hda },
5223 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
5224 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
5225 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
5226 { "drive", HAS_ARG, QEMU_OPTION_drive },
5227 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
5228 { "mtdblock", HAS_ARG, QEMU_OPTION_mtdblock },
5229 { "sd", HAS_ARG, QEMU_OPTION_sd },
5230 { "pflash", HAS_ARG, QEMU_OPTION_pflash },
5231 { "boot", HAS_ARG, QEMU_OPTION_boot },
5232 { "snapshot", 0, QEMU_OPTION_snapshot },
5234 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
5236 { "m", HAS_ARG, QEMU_OPTION_m },
5237 { "nographic", 0, QEMU_OPTION_nographic },
5238 { "portrait", 0, QEMU_OPTION_portrait },
5239 { "k", HAS_ARG, QEMU_OPTION_k },
5241 { "audio-help", 0, QEMU_OPTION_audio_help },
5242 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
5245 { "net", HAS_ARG, QEMU_OPTION_net},
5247 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
5248 { "bootp", HAS_ARG, QEMU_OPTION_bootp },
5250 { "smb", HAS_ARG, QEMU_OPTION_smb },
5252 { "redir", HAS_ARG, QEMU_OPTION_redir },
5254 { "bt", HAS_ARG, QEMU_OPTION_bt },
5256 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
5257 { "append", HAS_ARG, QEMU_OPTION_append },
5258 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
5260 { "S", 0, QEMU_OPTION_S },
5261 { "s", 0, QEMU_OPTION_s },
5262 { "p", HAS_ARG, QEMU_OPTION_p },
5263 { "d", HAS_ARG, QEMU_OPTION_d },
5264 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
5265 { "L", HAS_ARG, QEMU_OPTION_L },
5266 { "bios", HAS_ARG, QEMU_OPTION_bios },
5268 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
5269 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
5272 { "enable-kvm", 0, QEMU_OPTION_enable_kvm },
5274 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
5275 { "g", 1, QEMU_OPTION_g },
5277 { "localtime", 0, QEMU_OPTION_localtime },
5278 { "vga", HAS_ARG, QEMU_OPTION_vga },
5279 { "echr", HAS_ARG, QEMU_OPTION_echr },
5280 { "monitor", HAS_ARG, QEMU_OPTION_monitor },
5281 { "serial", HAS_ARG, QEMU_OPTION_serial },
5282 { "parallel", HAS_ARG, QEMU_OPTION_parallel },
5283 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
5284 { "full-screen", 0, QEMU_OPTION_full_screen },
5286 { "no-frame", 0, QEMU_OPTION_no_frame },
5287 { "alt-grab", 0, QEMU_OPTION_alt_grab },
5288 { "no-quit", 0, QEMU_OPTION_no_quit },
5290 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
5291 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
5292 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
5293 { "smp", HAS_ARG, QEMU_OPTION_smp },
5294 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
5295 #ifdef CONFIG_CURSES
5296 { "curses", 0, QEMU_OPTION_curses },
5298 { "uuid", HAS_ARG, QEMU_OPTION_uuid },
5300 /* temporary options */
5301 { "usb", 0, QEMU_OPTION_usb },
5302 { "no-acpi", 0, QEMU_OPTION_no_acpi },
5303 { "no-reboot", 0, QEMU_OPTION_no_reboot },
5304 { "no-shutdown", 0, QEMU_OPTION_no_shutdown },
5305 { "show-cursor", 0, QEMU_OPTION_show_cursor },
5306 { "daemonize", 0, QEMU_OPTION_daemonize },
5307 { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
5308 #if defined(TARGET_ARM) || defined(TARGET_M68K)
5309 { "semihosting", 0, QEMU_OPTION_semihosting },
5311 { "name", HAS_ARG, QEMU_OPTION_name },
5312 #if defined(TARGET_SPARC)
5313 { "prom-env", HAS_ARG, QEMU_OPTION_prom_env },
5315 #if defined(TARGET_ARM)
5316 { "old-param", 0, QEMU_OPTION_old_param },
5318 { "clock", HAS_ARG, QEMU_OPTION_clock },
5319 { "startdate", HAS_ARG, QEMU_OPTION_startdate },
5320 { "tb-size", HAS_ARG, QEMU_OPTION_tb_size },
5321 { "icount", HAS_ARG, QEMU_OPTION_icount },
5322 { "incoming", HAS_ARG, QEMU_OPTION_incoming },
5326 /* password input */
5328 int qemu_key_check(BlockDriverState *bs, const char *name)
5333 if (!bdrv_is_encrypted(bs))
5336 term_printf("%s is encrypted.\n", name);
5337 for(i = 0; i < 3; i++) {
5338 monitor_readline("Password: ", 1, password, sizeof(password));
5339 if (bdrv_set_key(bs, password) == 0)
5341 term_printf("invalid password\n");
5346 static BlockDriverState *get_bdrv(int index)
5348 if (index > nb_drives)
5350 return drives_table[index].bdrv;
5353 static void read_passwords(void)
5355 BlockDriverState *bs;
5358 for(i = 0; i < 6; i++) {
5361 qemu_key_check(bs, bdrv_get_device_name(bs));
5366 struct soundhw soundhw[] = {
5367 #ifdef HAS_AUDIO_CHOICE
5368 #if defined(TARGET_I386) || defined(TARGET_MIPS)
5374 { .init_isa = pcspk_audio_init }
5379 "Creative Sound Blaster 16",
5382 { .init_isa = SB16_init }
5385 #ifdef CONFIG_CS4231A
5391 { .init_isa = cs4231a_init }
5399 "Yamaha YMF262 (OPL3)",
5401 "Yamaha YM3812 (OPL2)",
5405 { .init_isa = Adlib_init }
5412 "Gravis Ultrasound GF1",
5415 { .init_isa = GUS_init }
5422 "Intel 82801AA AC97 Audio",
5425 { .init_pci = ac97_init }
5431 "ENSONIQ AudioPCI ES1370",
5434 { .init_pci = es1370_init }
5438 { NULL, NULL, 0, 0, { NULL } }
5441 static void select_soundhw (const char *optarg)
5445 if (*optarg == '?') {
5448 printf ("Valid sound card names (comma separated):\n");
5449 for (c = soundhw; c->name; ++c) {
5450 printf ("%-11s %s\n", c->name, c->descr);
5452 printf ("\n-soundhw all will enable all of the above\n");
5453 exit (*optarg != '?');
5461 if (!strcmp (optarg, "all")) {
5462 for (c = soundhw; c->name; ++c) {
5470 e = strchr (p, ',');
5471 l = !e ? strlen (p) : (size_t) (e - p);
5473 for (c = soundhw; c->name; ++c) {
5474 if (!strncmp (c->name, p, l)) {
5483 "Unknown sound card name (too big to show)\n");
5486 fprintf (stderr, "Unknown sound card name `%.*s'\n",
5491 p += l + (e != NULL);
5495 goto show_valid_cards;
5500 static void select_vgahw (const char *p)
5504 if (strstart(p, "std", &opts)) {
5505 cirrus_vga_enabled = 0;
5507 } else if (strstart(p, "cirrus", &opts)) {
5508 cirrus_vga_enabled = 1;
5510 } else if (strstart(p, "vmware", &opts)) {
5511 cirrus_vga_enabled = 0;
5515 fprintf(stderr, "Unknown vga type: %s\n", p);
5519 const char *nextopt;
5521 if (strstart(opts, ",retrace=", &nextopt)) {
5523 if (strstart(opts, "dumb", &nextopt))
5524 vga_retrace_method = VGA_RETRACE_DUMB;
5525 else if (strstart(opts, "precise", &nextopt))
5526 vga_retrace_method = VGA_RETRACE_PRECISE;
5527 else goto invalid_vga;
5528 } else goto invalid_vga;
5534 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
5536 exit(STATUS_CONTROL_C_EXIT);
5541 static int qemu_uuid_parse(const char *str, uint8_t *uuid)
5545 if(strlen(str) != 36)
5548 ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
5549 &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
5550 &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
5558 #define MAX_NET_CLIENTS 32
5562 static void termsig_handler(int signal)
5564 qemu_system_shutdown_request();
5567 static void termsig_setup(void)
5569 struct sigaction act;
5571 memset(&act, 0, sizeof(act));
5572 act.sa_handler = termsig_handler;
5573 sigaction(SIGINT, &act, NULL);
5574 sigaction(SIGHUP, &act, NULL);
5575 sigaction(SIGTERM, &act, NULL);
5580 int main(int argc, char **argv)
5582 #ifdef CONFIG_GDBSTUB
5584 const char *gdbstub_port;
5586 uint32_t boot_devices_bitmap = 0;
5588 int snapshot, linux_boot, net_boot;
5589 const char *initrd_filename;
5590 const char *kernel_filename, *kernel_cmdline;
5591 const char *boot_devices = "";
5592 DisplayState *ds = &display_state;
5593 int cyls, heads, secs, translation;
5594 const char *net_clients[MAX_NET_CLIENTS];
5596 const char *bt_opts[MAX_BT_CMDLINE];
5600 const char *r, *optarg;
5601 CharDriverState *monitor_hd;
5602 const char *monitor_device;
5603 const char *serial_devices[MAX_SERIAL_PORTS];
5604 int serial_device_index;
5605 const char *parallel_devices[MAX_PARALLEL_PORTS];
5606 int parallel_device_index;
5607 const char *loadvm = NULL;
5608 QEMUMachine *machine;
5609 const char *cpu_model;
5610 const char *usb_devices[MAX_USB_CMDLINE];
5611 int usb_devices_index;
5614 const char *pid_file = NULL;
5616 const char *incoming = NULL;
5618 LIST_INIT (&vm_change_state_head);
5621 struct sigaction act;
5622 sigfillset(&act.sa_mask);
5624 act.sa_handler = SIG_IGN;
5625 sigaction(SIGPIPE, &act, NULL);
5628 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
5629 /* Note: cpu_interrupt() is currently not SMP safe, so we force
5630 QEMU to run on a single CPU */
5635 h = GetCurrentProcess();
5636 if (GetProcessAffinityMask(h, &mask, &smask)) {
5637 for(i = 0; i < 32; i++) {
5638 if (mask & (1 << i))
5643 SetProcessAffinityMask(h, mask);
5649 register_machines();
5650 machine = first_machine;
5652 initrd_filename = NULL;
5654 vga_ram_size = VGA_RAM_SIZE;
5655 #ifdef CONFIG_GDBSTUB
5657 gdbstub_port = DEFAULT_GDBSTUB_PORT;
5662 kernel_filename = NULL;
5663 kernel_cmdline = "";
5664 cyls = heads = secs = 0;
5665 translation = BIOS_ATA_TRANSLATION_AUTO;
5666 monitor_device = "vc";
5668 serial_devices[0] = "vc:80Cx24C";
5669 for(i = 1; i < MAX_SERIAL_PORTS; i++)
5670 serial_devices[i] = NULL;
5671 serial_device_index = 0;
5673 parallel_devices[0] = "vc:640x480";
5674 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
5675 parallel_devices[i] = NULL;
5676 parallel_device_index = 0;
5678 usb_devices_index = 0;
5697 hda_index = drive_add(argv[optind++], HD_ALIAS, 0);
5699 const QEMUOption *popt;
5702 /* Treat --foo the same as -foo. */
5705 popt = qemu_options;
5708 fprintf(stderr, "%s: invalid option -- '%s'\n",
5712 if (!strcmp(popt->name, r + 1))
5716 if (popt->flags & HAS_ARG) {
5717 if (optind >= argc) {
5718 fprintf(stderr, "%s: option '%s' requires an argument\n",
5722 optarg = argv[optind++];
5727 switch(popt->index) {
5729 machine = find_machine(optarg);
5732 printf("Supported machines are:\n");
5733 for(m = first_machine; m != NULL; m = m->next) {
5734 printf("%-10s %s%s\n",
5736 m == first_machine ? " (default)" : "");
5738 exit(*optarg != '?');
5741 case QEMU_OPTION_cpu:
5742 /* hw initialization will check this */
5743 if (*optarg == '?') {
5744 /* XXX: implement xxx_cpu_list for targets that still miss it */
5745 #if defined(cpu_list)
5746 cpu_list(stdout, &fprintf);
5753 case QEMU_OPTION_initrd:
5754 initrd_filename = optarg;
5756 case QEMU_OPTION_hda:
5758 hda_index = drive_add(optarg, HD_ALIAS, 0);
5760 hda_index = drive_add(optarg, HD_ALIAS
5761 ",cyls=%d,heads=%d,secs=%d%s",
5762 0, cyls, heads, secs,
5763 translation == BIOS_ATA_TRANSLATION_LBA ?
5765 translation == BIOS_ATA_TRANSLATION_NONE ?
5766 ",trans=none" : "");
5768 case QEMU_OPTION_hdb:
5769 case QEMU_OPTION_hdc:
5770 case QEMU_OPTION_hdd:
5771 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
5773 case QEMU_OPTION_drive:
5774 drive_add(NULL, "%s", optarg);
5776 case QEMU_OPTION_mtdblock:
5777 drive_add(optarg, MTD_ALIAS);
5779 case QEMU_OPTION_sd:
5780 drive_add(optarg, SD_ALIAS);
5782 case QEMU_OPTION_pflash:
5783 drive_add(optarg, PFLASH_ALIAS);
5785 case QEMU_OPTION_snapshot:
5788 case QEMU_OPTION_hdachs:
5792 cyls = strtol(p, (char **)&p, 0);
5793 if (cyls < 1 || cyls > 16383)
5798 heads = strtol(p, (char **)&p, 0);
5799 if (heads < 1 || heads > 16)
5804 secs = strtol(p, (char **)&p, 0);
5805 if (secs < 1 || secs > 63)
5809 if (!strcmp(p, "none"))
5810 translation = BIOS_ATA_TRANSLATION_NONE;
5811 else if (!strcmp(p, "lba"))
5812 translation = BIOS_ATA_TRANSLATION_LBA;
5813 else if (!strcmp(p, "auto"))
5814 translation = BIOS_ATA_TRANSLATION_AUTO;
5817 } else if (*p != '\0') {
5819 fprintf(stderr, "qemu: invalid physical CHS format\n");
5822 if (hda_index != -1)
5823 snprintf(drives_opt[hda_index].opt,
5824 sizeof(drives_opt[hda_index].opt),
5825 HD_ALIAS ",cyls=%d,heads=%d,secs=%d%s",
5826 0, cyls, heads, secs,
5827 translation == BIOS_ATA_TRANSLATION_LBA ?
5829 translation == BIOS_ATA_TRANSLATION_NONE ?
5830 ",trans=none" : "");
5833 case QEMU_OPTION_nographic:
5836 #ifdef CONFIG_CURSES
5837 case QEMU_OPTION_curses:
5841 case QEMU_OPTION_portrait:
5844 case QEMU_OPTION_kernel:
5845 kernel_filename = optarg;
5847 case QEMU_OPTION_append:
5848 kernel_cmdline = optarg;
5850 case QEMU_OPTION_cdrom:
5851 drive_add(optarg, CDROM_ALIAS);
5853 case QEMU_OPTION_boot:
5854 boot_devices = optarg;
5855 /* We just do some generic consistency checks */
5857 /* Could easily be extended to 64 devices if needed */
5860 boot_devices_bitmap = 0;
5861 for (p = boot_devices; *p != '\0'; p++) {
5862 /* Allowed boot devices are:
5863 * a b : floppy disk drives
5864 * c ... f : IDE disk drives
5865 * g ... m : machine implementation dependant drives
5866 * n ... p : network devices
5867 * It's up to each machine implementation to check
5868 * if the given boot devices match the actual hardware
5869 * implementation and firmware features.
5871 if (*p < 'a' || *p > 'q') {
5872 fprintf(stderr, "Invalid boot device '%c'\n", *p);
5875 if (boot_devices_bitmap & (1 << (*p - 'a'))) {
5877 "Boot device '%c' was given twice\n",*p);
5880 boot_devices_bitmap |= 1 << (*p - 'a');
5884 case QEMU_OPTION_fda:
5885 case QEMU_OPTION_fdb:
5886 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
5889 case QEMU_OPTION_no_fd_bootchk:
5893 case QEMU_OPTION_net:
5894 if (nb_net_clients >= MAX_NET_CLIENTS) {
5895 fprintf(stderr, "qemu: too many network clients\n");
5898 net_clients[nb_net_clients] = optarg;
5902 case QEMU_OPTION_tftp:
5903 tftp_prefix = optarg;
5905 case QEMU_OPTION_bootp:
5906 bootp_filename = optarg;
5909 case QEMU_OPTION_smb:
5910 net_slirp_smb(optarg);
5913 case QEMU_OPTION_redir:
5914 net_slirp_redir(optarg);
5917 case QEMU_OPTION_bt:
5918 if (nb_bt_opts >= MAX_BT_CMDLINE) {
5919 fprintf(stderr, "qemu: too many bluetooth options\n");
5922 bt_opts[nb_bt_opts++] = optarg;
5925 case QEMU_OPTION_audio_help:
5929 case QEMU_OPTION_soundhw:
5930 select_soundhw (optarg);
5936 case QEMU_OPTION_m: {
5940 value = strtoul(optarg, &ptr, 10);
5942 case 0: case 'M': case 'm':
5949 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
5953 /* On 32-bit hosts, QEMU is limited by virtual address space */
5954 if (value > (2047 << 20)
5956 && HOST_LONG_BITS == 32
5959 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
5962 if (value != (uint64_t)(ram_addr_t)value) {
5963 fprintf(stderr, "qemu: ram size too large\n");
5972 const CPULogItem *item;
5974 mask = cpu_str_to_log_mask(optarg);
5976 printf("Log items (comma separated):\n");
5977 for(item = cpu_log_items; item->mask != 0; item++) {
5978 printf("%-10s %s\n", item->name, item->help);
5985 #ifdef CONFIG_GDBSTUB
5990 gdbstub_port = optarg;
5996 case QEMU_OPTION_bios:
6003 keyboard_layout = optarg;
6005 case QEMU_OPTION_localtime:
6008 case QEMU_OPTION_vga:
6009 select_vgahw (optarg);
6016 w = strtol(p, (char **)&p, 10);
6019 fprintf(stderr, "qemu: invalid resolution or depth\n");
6025 h = strtol(p, (char **)&p, 10);
6030 depth = strtol(p, (char **)&p, 10);
6031 if (depth != 8 && depth != 15 && depth != 16 &&
6032 depth != 24 && depth != 32)
6034 } else if (*p == '\0') {
6035 depth = graphic_depth;
6042 graphic_depth = depth;
6045 case QEMU_OPTION_echr:
6048 term_escape_char = strtol(optarg, &r, 0);
6050 printf("Bad argument to echr\n");
6053 case QEMU_OPTION_monitor:
6054 monitor_device = optarg;
6056 case QEMU_OPTION_serial:
6057 if (serial_device_index >= MAX_SERIAL_PORTS) {
6058 fprintf(stderr, "qemu: too many serial ports\n");
6061 serial_devices[serial_device_index] = optarg;
6062 serial_device_index++;
6064 case QEMU_OPTION_parallel:
6065 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
6066 fprintf(stderr, "qemu: too many parallel ports\n");
6069 parallel_devices[parallel_device_index] = optarg;
6070 parallel_device_index++;
6072 case QEMU_OPTION_loadvm:
6075 case QEMU_OPTION_full_screen:
6079 case QEMU_OPTION_no_frame:
6082 case QEMU_OPTION_alt_grab:
6085 case QEMU_OPTION_no_quit:
6089 case QEMU_OPTION_pidfile:
6093 case QEMU_OPTION_win2k_hack:
6094 win2k_install_hack = 1;
6098 case QEMU_OPTION_no_kqemu:
6101 case QEMU_OPTION_kernel_kqemu:
6106 case QEMU_OPTION_enable_kvm:
6113 case QEMU_OPTION_usb:
6116 case QEMU_OPTION_usbdevice:
6118 if (usb_devices_index >= MAX_USB_CMDLINE) {
6119 fprintf(stderr, "Too many USB devices\n");
6122 usb_devices[usb_devices_index] = optarg;
6123 usb_devices_index++;
6125 case QEMU_OPTION_smp:
6126 smp_cpus = atoi(optarg);
6128 fprintf(stderr, "Invalid number of CPUs\n");
6132 case QEMU_OPTION_vnc:
6133 vnc_display = optarg;
6135 case QEMU_OPTION_no_acpi:
6138 case QEMU_OPTION_no_reboot:
6141 case QEMU_OPTION_no_shutdown:
6144 case QEMU_OPTION_show_cursor:
6147 case QEMU_OPTION_uuid:
6148 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
6149 fprintf(stderr, "Fail to parse UUID string."
6150 " Wrong format.\n");
6154 case QEMU_OPTION_daemonize:
6157 case QEMU_OPTION_option_rom:
6158 if (nb_option_roms >= MAX_OPTION_ROMS) {
6159 fprintf(stderr, "Too many option ROMs\n");
6162 option_rom[nb_option_roms] = optarg;
6165 case QEMU_OPTION_semihosting:
6166 semihosting_enabled = 1;
6168 case QEMU_OPTION_name:
6172 case QEMU_OPTION_prom_env:
6173 if (nb_prom_envs >= MAX_PROM_ENVS) {
6174 fprintf(stderr, "Too many prom variables\n");
6177 prom_envs[nb_prom_envs] = optarg;
6182 case QEMU_OPTION_old_param:
6186 case QEMU_OPTION_clock:
6187 configure_alarms(optarg);
6189 case QEMU_OPTION_startdate:
6192 time_t rtc_start_date;
6193 if (!strcmp(optarg, "now")) {
6194 rtc_date_offset = -1;
6196 if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
6204 } else if (sscanf(optarg, "%d-%d-%d",
6207 &tm.tm_mday) == 3) {
6216 rtc_start_date = mktimegm(&tm);
6217 if (rtc_start_date == -1) {
6219 fprintf(stderr, "Invalid date format. Valid format are:\n"
6220 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
6223 rtc_date_offset = time(NULL) - rtc_start_date;
6227 case QEMU_OPTION_tb_size:
6228 tb_size = strtol(optarg, NULL, 0);
6232 case QEMU_OPTION_icount:
6234 if (strcmp(optarg, "auto") == 0) {
6235 icount_time_shift = -1;
6237 icount_time_shift = strtol(optarg, NULL, 0);
6240 case QEMU_OPTION_incoming:
6247 #if defined(CONFIG_KVM) && defined(USE_KQEMU)
6248 if (kvm_allowed && kqemu_allowed) {
6250 "You can not enable both KVM and kqemu at the same time\n");
6255 machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
6256 if (smp_cpus > machine->max_cpus) {
6257 fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
6258 "supported by machine `%s' (%d)\n", smp_cpus, machine->name,
6264 if (serial_device_index == 0)
6265 serial_devices[0] = "stdio";
6266 if (parallel_device_index == 0)
6267 parallel_devices[0] = "null";
6268 if (strncmp(monitor_device, "vc", 2) == 0)
6269 monitor_device = "stdio";
6276 if (pipe(fds) == -1)
6287 len = read(fds[0], &status, 1);
6288 if (len == -1 && (errno == EINTR))
6293 else if (status == 1) {
6294 fprintf(stderr, "Could not acquire pidfile\n");
6311 signal(SIGTSTP, SIG_IGN);
6312 signal(SIGTTOU, SIG_IGN);
6313 signal(SIGTTIN, SIG_IGN);
6317 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
6320 write(fds[1], &status, 1);
6322 fprintf(stderr, "Could not acquire pid file\n");
6330 linux_boot = (kernel_filename != NULL);
6331 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
6333 if (!linux_boot && net_boot == 0 &&
6334 !machine->nodisk_ok && nb_drives_opt == 0)
6337 if (!linux_boot && *kernel_cmdline != '\0') {
6338 fprintf(stderr, "-append only allowed with -kernel option\n");
6342 if (!linux_boot && initrd_filename != NULL) {
6343 fprintf(stderr, "-initrd only allowed with -kernel option\n");
6347 /* boot to floppy or the default cd if no hard disk defined yet */
6348 if (!boot_devices[0]) {
6349 boot_devices = "cad";
6351 setvbuf(stdout, NULL, _IOLBF, 0);
6354 if (init_timer_alarm() < 0) {
6355 fprintf(stderr, "could not initialize alarm timer\n");
6358 if (use_icount && icount_time_shift < 0) {
6360 /* 125MIPS seems a reasonable initial guess at the guest speed.
6361 It will be corrected fairly quickly anyway. */
6362 icount_time_shift = 3;
6363 init_icount_adjust();
6370 /* init network clients */
6371 if (nb_net_clients == 0) {
6372 /* if no clients, we use a default config */
6373 net_clients[nb_net_clients++] = "nic";
6375 net_clients[nb_net_clients++] = "user";
6379 for(i = 0;i < nb_net_clients; i++) {
6380 if (net_client_parse(net_clients[i]) < 0)
6386 /* XXX: this should be moved in the PC machine instantiation code */
6387 if (net_boot != 0) {
6389 for (i = 0; i < nb_nics && i < 4; i++) {
6390 const char *model = nd_table[i].model;
6392 if (net_boot & (1 << i)) {
6395 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
6396 if (get_image_size(buf) > 0) {
6397 if (nb_option_roms >= MAX_OPTION_ROMS) {
6398 fprintf(stderr, "Too many option ROMs\n");
6401 option_rom[nb_option_roms] = strdup(buf);
6408 fprintf(stderr, "No valid PXE rom found for network device\n");
6414 /* init the bluetooth world */
6415 for (i = 0; i < nb_bt_opts; i++)
6416 if (bt_parse(bt_opts[i]))
6419 /* init the memory */
6420 phys_ram_size = machine->ram_require & ~RAMSIZE_FIXED;
6422 if (machine->ram_require & RAMSIZE_FIXED) {
6424 if (ram_size < phys_ram_size) {
6425 fprintf(stderr, "Machine `%s' requires %llu bytes of memory\n",
6426 machine->name, (unsigned long long) phys_ram_size);
6430 phys_ram_size = ram_size;
6432 ram_size = phys_ram_size;
6435 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
6437 phys_ram_size += ram_size;
6440 phys_ram_base = qemu_vmalloc(phys_ram_size);
6441 if (!phys_ram_base) {
6442 fprintf(stderr, "Could not allocate physical memory\n");
6446 /* init the dynamic translator */
6447 cpu_exec_init_all(tb_size * 1024 * 1024);
6451 /* we always create the cdrom drive, even if no disk is there */
6453 if (nb_drives_opt < MAX_DRIVES)
6454 drive_add(NULL, CDROM_ALIAS);
6456 /* we always create at least one floppy */
6458 if (nb_drives_opt < MAX_DRIVES)
6459 drive_add(NULL, FD_ALIAS, 0);
6461 /* we always create one sd slot, even if no card is in it */
6463 if (nb_drives_opt < MAX_DRIVES)
6464 drive_add(NULL, SD_ALIAS);
6466 /* open the virtual block devices */
6468 for(i = 0; i < nb_drives_opt; i++)
6469 if (drive_init(&drives_opt[i], snapshot, machine) == -1)
6472 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
6473 register_savevm_live("ram", 0, 3, ram_save_live, NULL, ram_load, NULL);
6476 memset(&display_state, 0, sizeof(display_state));
6479 fprintf(stderr, "fatal: -nographic can't be used with -curses\n");
6482 /* nearly nothing to do */
6483 dumb_display_init(ds);
6484 } else if (vnc_display != NULL) {
6485 vnc_display_init(ds);
6486 if (vnc_display_open(ds, vnc_display) < 0)
6489 #if defined(CONFIG_CURSES)
6491 curses_display_init(ds, full_screen);
6495 #if defined(CONFIG_SDL)
6496 sdl_display_init(ds, full_screen, no_frame);
6497 #elif defined(CONFIG_COCOA)
6498 cocoa_display_init(ds, full_screen);
6500 dumb_display_init(ds);
6505 /* must be after terminal init, SDL library changes signal handlers */
6509 /* Maintain compatibility with multiple stdio monitors */
6510 if (!strcmp(monitor_device,"stdio")) {
6511 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
6512 const char *devname = serial_devices[i];
6513 if (devname && !strcmp(devname,"mon:stdio")) {
6514 monitor_device = NULL;
6516 } else if (devname && !strcmp(devname,"stdio")) {
6517 monitor_device = NULL;
6518 serial_devices[i] = "mon:stdio";
6523 if (monitor_device) {
6524 monitor_hd = qemu_chr_open("monitor", monitor_device);
6526 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
6529 monitor_init(monitor_hd, !nographic);
6532 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
6533 const char *devname = serial_devices[i];
6534 if (devname && strcmp(devname, "none")) {
6536 snprintf(label, sizeof(label), "serial%d", i);
6537 serial_hds[i] = qemu_chr_open(label, devname);
6538 if (!serial_hds[i]) {
6539 fprintf(stderr, "qemu: could not open serial device '%s'\n",
6543 if (strstart(devname, "vc", 0))
6544 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
6548 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
6549 const char *devname = parallel_devices[i];
6550 if (devname && strcmp(devname, "none")) {
6552 snprintf(label, sizeof(label), "parallel%d", i);
6553 parallel_hds[i] = qemu_chr_open(label, devname);
6554 if (!parallel_hds[i]) {
6555 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
6559 if (strstart(devname, "vc", 0))
6560 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
6564 if (kvm_enabled()) {
6567 ret = kvm_init(smp_cpus);
6569 fprintf(stderr, "failed to initialize KVM\n");
6574 machine->init(ram_size, vga_ram_size, boot_devices, ds,
6575 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
6577 /* init USB devices */
6579 for(i = 0; i < usb_devices_index; i++) {
6580 if (usb_device_add(usb_devices[i]) < 0) {
6581 fprintf(stderr, "Warning: could not add USB device %s\n",
6587 if (display_state.dpy_refresh) {
6588 display_state.gui_timer = qemu_new_timer(rt_clock, gui_update, &display_state);
6589 qemu_mod_timer(display_state.gui_timer, qemu_get_clock(rt_clock));
6592 #ifdef CONFIG_GDBSTUB
6594 /* XXX: use standard host:port notation and modify options
6596 if (gdbserver_start(gdbstub_port) < 0) {
6597 fprintf(stderr, "qemu: could not open gdbstub device on port '%s'\n",
6608 autostart = 0; /* fixme how to deal with -daemonize */
6609 qemu_start_incoming_migration(incoming);
6613 /* XXX: simplify init */
6626 len = write(fds[1], &status, 1);
6627 if (len == -1 && (errno == EINTR))
6634 TFR(fd = open("/dev/null", O_RDWR));