4 * Copyright (c) 2003-2005 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
34 #include <sys/times.h>
39 #include <sys/ioctl.h>
40 #include <sys/socket.h>
41 #include <netinet/in.h>
50 #include <linux/if_tun.h>
53 #include <linux/rtc.h>
57 #if defined(CONFIG_SLIRP)
63 #include <sys/timeb.h>
65 #define getopt_long_only getopt_long
66 #define memalign(align, size) malloc(size)
73 #endif /* CONFIG_SDL */
77 #define main qemu_main
78 #endif /* CONFIG_COCOA */
86 #define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
88 //#define DEBUG_UNUSED_IOPORT
89 //#define DEBUG_IOPORT
91 #if !defined(CONFIG_SOFTMMU)
92 #define PHYS_RAM_MAX_SIZE (256 * 1024 * 1024)
94 #define PHYS_RAM_MAX_SIZE (2047 * 1024 * 1024)
98 #define DEFAULT_RAM_SIZE 144
100 #define DEFAULT_RAM_SIZE 128
103 #define GUI_REFRESH_INTERVAL 30
105 /* XXX: use a two level table to limit memory usage */
106 #define MAX_IOPORTS 65536
108 const char *bios_dir = CONFIG_QEMU_SHAREDIR;
109 char phys_ram_file[1024];
110 CPUState *global_env;
111 CPUState *cpu_single_env;
112 void *ioport_opaque[MAX_IOPORTS];
113 IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
114 IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
115 BlockDriverState *bs_table[MAX_DISKS], *fd_table[MAX_FD];
118 static DisplayState display_state;
120 const char* keyboard_layout = NULL;
121 int64_t ticks_per_sec;
122 int boot_device = 'c';
124 static char network_script[1024];
125 int pit_min_timer_count = 0;
127 NetDriverState nd_table[MAX_NICS];
128 QEMUTimer *gui_timer;
130 int audio_enabled = 0;
131 int sb16_enabled = 1;
132 int adlib_enabled = 1;
135 int prep_enabled = 0;
137 int cirrus_vga_enabled = 1;
139 int graphic_width = 1024;
140 int graphic_height = 768;
142 int graphic_width = 800;
143 int graphic_height = 600;
145 int graphic_depth = 15;
147 TextConsole *vga_console;
148 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
149 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
151 int win2k_install_hack = 0;
154 /***********************************************************/
155 /* x86 ISA bus support */
157 target_phys_addr_t isa_mem_base = 0;
160 uint32_t default_ioport_readb(void *opaque, uint32_t address)
162 #ifdef DEBUG_UNUSED_IOPORT
163 fprintf(stderr, "inb: port=0x%04x\n", address);
168 void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
170 #ifdef DEBUG_UNUSED_IOPORT
171 fprintf(stderr, "outb: port=0x%04x data=0x%02x\n", address, data);
175 /* default is to make two byte accesses */
176 uint32_t default_ioport_readw(void *opaque, uint32_t address)
179 data = ioport_read_table[0][address](ioport_opaque[address], address);
180 address = (address + 1) & (MAX_IOPORTS - 1);
181 data |= ioport_read_table[0][address](ioport_opaque[address], address) << 8;
185 void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
187 ioport_write_table[0][address](ioport_opaque[address], address, data & 0xff);
188 address = (address + 1) & (MAX_IOPORTS - 1);
189 ioport_write_table[0][address](ioport_opaque[address], address, (data >> 8) & 0xff);
192 uint32_t default_ioport_readl(void *opaque, uint32_t address)
194 #ifdef DEBUG_UNUSED_IOPORT
195 fprintf(stderr, "inl: port=0x%04x\n", address);
200 void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
202 #ifdef DEBUG_UNUSED_IOPORT
203 fprintf(stderr, "outl: port=0x%04x data=0x%02x\n", address, data);
207 void init_ioports(void)
211 for(i = 0; i < MAX_IOPORTS; i++) {
212 ioport_read_table[0][i] = default_ioport_readb;
213 ioport_write_table[0][i] = default_ioport_writeb;
214 ioport_read_table[1][i] = default_ioport_readw;
215 ioport_write_table[1][i] = default_ioport_writew;
216 ioport_read_table[2][i] = default_ioport_readl;
217 ioport_write_table[2][i] = default_ioport_writel;
221 /* size is the word size in byte */
222 int register_ioport_read(int start, int length, int size,
223 IOPortReadFunc *func, void *opaque)
229 } else if (size == 2) {
231 } else if (size == 4) {
234 hw_error("register_ioport_read: invalid size");
237 for(i = start; i < start + length; i += size) {
238 ioport_read_table[bsize][i] = func;
239 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
240 hw_error("register_ioport_read: invalid opaque");
241 ioport_opaque[i] = opaque;
246 /* size is the word size in byte */
247 int register_ioport_write(int start, int length, int size,
248 IOPortWriteFunc *func, void *opaque)
254 } else if (size == 2) {
256 } else if (size == 4) {
259 hw_error("register_ioport_write: invalid size");
262 for(i = start; i < start + length; i += size) {
263 ioport_write_table[bsize][i] = func;
264 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
265 hw_error("register_ioport_read: invalid opaque");
266 ioport_opaque[i] = opaque;
271 void isa_unassign_ioport(int start, int length)
275 for(i = start; i < start + length; i++) {
276 ioport_read_table[0][i] = default_ioport_readb;
277 ioport_read_table[1][i] = default_ioport_readw;
278 ioport_read_table[2][i] = default_ioport_readl;
280 ioport_write_table[0][i] = default_ioport_writeb;
281 ioport_write_table[1][i] = default_ioport_writew;
282 ioport_write_table[2][i] = default_ioport_writel;
286 /***********************************************************/
288 void pstrcpy(char *buf, int buf_size, const char *str)
298 if (c == 0 || q >= buf + buf_size - 1)
305 /* strcat and truncate. */
306 char *pstrcat(char *buf, int buf_size, const char *s)
311 pstrcpy(buf + len, buf_size - len, s);
315 int strstart(const char *str, const char *val, const char **ptr)
331 /* return the size or -1 if error */
332 int get_image_size(const char *filename)
335 fd = open(filename, O_RDONLY | O_BINARY);
338 size = lseek(fd, 0, SEEK_END);
343 /* return the size or -1 if error */
344 int load_image(const char *filename, uint8_t *addr)
347 fd = open(filename, O_RDONLY | O_BINARY);
350 size = lseek(fd, 0, SEEK_END);
351 lseek(fd, 0, SEEK_SET);
352 if (read(fd, addr, size) != size) {
360 void cpu_outb(CPUState *env, int addr, int val)
363 if (loglevel & CPU_LOG_IOPORT)
364 fprintf(logfile, "outb: %04x %02x\n", addr, val);
366 ioport_write_table[0][addr](ioport_opaque[addr], addr, val);
369 void cpu_outw(CPUState *env, int addr, int val)
372 if (loglevel & CPU_LOG_IOPORT)
373 fprintf(logfile, "outw: %04x %04x\n", addr, val);
375 ioport_write_table[1][addr](ioport_opaque[addr], addr, val);
378 void cpu_outl(CPUState *env, int addr, int val)
381 if (loglevel & CPU_LOG_IOPORT)
382 fprintf(logfile, "outl: %04x %08x\n", addr, val);
384 ioport_write_table[2][addr](ioport_opaque[addr], addr, val);
387 int cpu_inb(CPUState *env, int addr)
390 val = ioport_read_table[0][addr](ioport_opaque[addr], addr);
392 if (loglevel & CPU_LOG_IOPORT)
393 fprintf(logfile, "inb : %04x %02x\n", addr, val);
398 int cpu_inw(CPUState *env, int addr)
401 val = ioport_read_table[1][addr](ioport_opaque[addr], addr);
403 if (loglevel & CPU_LOG_IOPORT)
404 fprintf(logfile, "inw : %04x %04x\n", addr, val);
409 int cpu_inl(CPUState *env, int addr)
412 val = ioport_read_table[2][addr](ioport_opaque[addr], addr);
414 if (loglevel & CPU_LOG_IOPORT)
415 fprintf(logfile, "inl : %04x %08x\n", addr, val);
420 /***********************************************************/
421 void hw_error(const char *fmt, ...)
426 fprintf(stderr, "qemu: hardware error: ");
427 vfprintf(stderr, fmt, ap);
428 fprintf(stderr, "\n");
430 cpu_dump_state(global_env, stderr, fprintf, X86_DUMP_FPU | X86_DUMP_CCOP);
432 cpu_dump_state(global_env, stderr, fprintf, 0);
438 /***********************************************************/
441 static QEMUPutKBDEvent *qemu_put_kbd_event;
442 static void *qemu_put_kbd_event_opaque;
443 static QEMUPutMouseEvent *qemu_put_mouse_event;
444 static void *qemu_put_mouse_event_opaque;
446 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
448 qemu_put_kbd_event_opaque = opaque;
449 qemu_put_kbd_event = func;
452 void qemu_add_mouse_event_handler(QEMUPutMouseEvent *func, void *opaque)
454 qemu_put_mouse_event_opaque = opaque;
455 qemu_put_mouse_event = func;
458 void kbd_put_keycode(int keycode)
460 if (qemu_put_kbd_event) {
461 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
465 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
467 if (qemu_put_mouse_event) {
468 qemu_put_mouse_event(qemu_put_mouse_event_opaque,
469 dx, dy, dz, buttons_state);
473 /***********************************************************/
476 #if defined(__powerpc__)
478 static inline uint32_t get_tbl(void)
481 asm volatile("mftb %0" : "=r" (tbl));
485 static inline uint32_t get_tbu(void)
488 asm volatile("mftbu %0" : "=r" (tbl));
492 int64_t cpu_get_real_ticks(void)
495 /* NOTE: we test if wrapping has occurred */
501 return ((int64_t)h << 32) | l;
504 #elif defined(__i386__)
506 int64_t cpu_get_real_ticks(void)
509 asm volatile ("rdtsc" : "=A" (val));
513 #elif defined(__x86_64__)
515 int64_t cpu_get_real_ticks(void)
519 asm volatile("rdtsc" : "=a" (low), "=d" (high));
526 #elif defined(__ia64)
528 int64_t cpu_get_real_ticks(void)
531 asm volatile ("mov %0 = ar.itc" : "=r"(val) :: "memory");
536 #error unsupported CPU
539 static int64_t cpu_ticks_offset;
540 static int cpu_ticks_enabled;
542 static inline int64_t cpu_get_ticks(void)
544 if (!cpu_ticks_enabled) {
545 return cpu_ticks_offset;
547 return cpu_get_real_ticks() + cpu_ticks_offset;
551 /* enable cpu_get_ticks() */
552 void cpu_enable_ticks(void)
554 if (!cpu_ticks_enabled) {
555 cpu_ticks_offset -= cpu_get_real_ticks();
556 cpu_ticks_enabled = 1;
560 /* disable cpu_get_ticks() : the clock is stopped. You must not call
561 cpu_get_ticks() after that. */
562 void cpu_disable_ticks(void)
564 if (cpu_ticks_enabled) {
565 cpu_ticks_offset = cpu_get_ticks();
566 cpu_ticks_enabled = 0;
570 static int64_t get_clock(void)
575 return ((int64_t)tb.time * 1000 + (int64_t)tb.millitm) * 1000;
578 gettimeofday(&tv, NULL);
579 return tv.tv_sec * 1000000LL + tv.tv_usec;
583 void cpu_calibrate_ticks(void)
588 ticks = cpu_get_real_ticks();
594 usec = get_clock() - usec;
595 ticks = cpu_get_real_ticks() - ticks;
596 ticks_per_sec = (ticks * 1000000LL + (usec >> 1)) / usec;
599 /* compute with 96 bit intermediate result: (a*b)/c */
600 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
605 #ifdef WORDS_BIGENDIAN
615 rl = (uint64_t)u.l.low * (uint64_t)b;
616 rh = (uint64_t)u.l.high * (uint64_t)b;
619 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
623 #define QEMU_TIMER_REALTIME 0
624 #define QEMU_TIMER_VIRTUAL 1
628 /* XXX: add frequency */
636 struct QEMUTimer *next;
642 static QEMUTimer *active_timers[2];
644 static MMRESULT timerID;
646 /* frequency of the times() clock tick */
647 static int timer_freq;
650 QEMUClock *qemu_new_clock(int type)
653 clock = qemu_mallocz(sizeof(QEMUClock));
660 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
664 ts = qemu_mallocz(sizeof(QEMUTimer));
671 void qemu_free_timer(QEMUTimer *ts)
676 /* stop a timer, but do not dealloc it */
677 void qemu_del_timer(QEMUTimer *ts)
681 /* NOTE: this code must be signal safe because
682 qemu_timer_expired() can be called from a signal. */
683 pt = &active_timers[ts->clock->type];
696 /* modify the current timer so that it will be fired when current_time
697 >= expire_time. The corresponding callback will be called. */
698 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
704 /* add the timer in the sorted list */
705 /* NOTE: this code must be signal safe because
706 qemu_timer_expired() can be called from a signal. */
707 pt = &active_timers[ts->clock->type];
712 if (t->expire_time > expire_time)
716 ts->expire_time = expire_time;
721 int qemu_timer_pending(QEMUTimer *ts)
724 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
731 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
735 return (timer_head->expire_time <= current_time);
738 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
744 if (!ts || ts->expire_time > current_time)
746 /* remove timer from the list before calling the callback */
747 *ptimer_head = ts->next;
750 /* run the callback (the timer list can be modified) */
755 int64_t qemu_get_clock(QEMUClock *clock)
757 switch(clock->type) {
758 case QEMU_TIMER_REALTIME:
760 return GetTickCount();
765 /* Note that using gettimeofday() is not a good solution
766 for timers because its value change when the date is
768 if (timer_freq == 100) {
769 return times(&tp) * 10;
771 return ((int64_t)times(&tp) * 1000) / timer_freq;
776 case QEMU_TIMER_VIRTUAL:
777 return cpu_get_ticks();
782 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
784 uint64_t expire_time;
786 if (qemu_timer_pending(ts)) {
787 expire_time = ts->expire_time;
791 qemu_put_be64(f, expire_time);
794 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
796 uint64_t expire_time;
798 expire_time = qemu_get_be64(f);
799 if (expire_time != -1) {
800 qemu_mod_timer(ts, expire_time);
806 static void timer_save(QEMUFile *f, void *opaque)
808 if (cpu_ticks_enabled) {
809 hw_error("cannot save state if virtual timers are running");
811 qemu_put_be64s(f, &cpu_ticks_offset);
812 qemu_put_be64s(f, &ticks_per_sec);
815 static int timer_load(QEMUFile *f, void *opaque, int version_id)
819 if (cpu_ticks_enabled) {
822 qemu_get_be64s(f, &cpu_ticks_offset);
823 qemu_get_be64s(f, &ticks_per_sec);
828 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
829 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
831 static void host_alarm_handler(int host_signum)
835 #define DISP_FREQ 1000
837 static int64_t delta_min = INT64_MAX;
838 static int64_t delta_max, delta_cum, last_clock, delta, ti;
840 ti = qemu_get_clock(vm_clock);
841 if (last_clock != 0) {
842 delta = ti - last_clock;
843 if (delta < delta_min)
845 if (delta > delta_max)
848 if (++count == DISP_FREQ) {
849 printf("timer: min=%lld us max=%lld us avg=%lld us avg_freq=%0.3f Hz\n",
850 muldiv64(delta_min, 1000000, ticks_per_sec),
851 muldiv64(delta_max, 1000000, ticks_per_sec),
852 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
853 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
855 delta_min = INT64_MAX;
863 if (qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
864 qemu_get_clock(vm_clock)) ||
865 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
866 qemu_get_clock(rt_clock))) {
867 /* stop the cpu because a timer occured */
868 cpu_interrupt(global_env, CPU_INTERRUPT_EXIT);
874 #if defined(__linux__)
876 #define RTC_FREQ 1024
880 static int start_rtc_timer(void)
882 rtc_fd = open("/dev/rtc", O_RDONLY);
885 if (ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
886 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
887 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
888 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
891 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
896 pit_min_timer_count = PIT_FREQ / RTC_FREQ;
902 static int start_rtc_timer(void)
907 #endif /* !defined(__linux__) */
909 #endif /* !defined(_WIN32) */
911 static void init_timers(void)
913 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
914 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
919 timerID = timeSetEvent(10, // interval (ms)
921 host_alarm_handler, // function
922 (DWORD)&count, // user parameter
923 TIME_PERIODIC | TIME_CALLBACK_FUNCTION);
925 perror("failed timer alarm");
929 pit_min_timer_count = ((uint64_t)10000 * PIT_FREQ) / 1000000;
932 struct sigaction act;
933 struct itimerval itv;
935 /* get times() syscall frequency */
936 timer_freq = sysconf(_SC_CLK_TCK);
939 sigfillset(&act.sa_mask);
941 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
942 act.sa_flags |= SA_ONSTACK;
944 act.sa_handler = host_alarm_handler;
945 sigaction(SIGALRM, &act, NULL);
947 itv.it_interval.tv_sec = 0;
948 itv.it_interval.tv_usec = 999; /* for i386 kernel 2.6 to get 1 ms */
949 itv.it_value.tv_sec = 0;
950 itv.it_value.tv_usec = 10 * 1000;
951 setitimer(ITIMER_REAL, &itv, NULL);
952 /* we probe the tick duration of the kernel to inform the user if
953 the emulated kernel requested a too high timer frequency */
954 getitimer(ITIMER_REAL, &itv);
956 #if defined(__linux__)
957 if (itv.it_interval.tv_usec > 1000) {
958 /* try to use /dev/rtc to have a faster timer */
959 if (start_rtc_timer() < 0)
962 itv.it_interval.tv_sec = 0;
963 itv.it_interval.tv_usec = 0;
964 itv.it_value.tv_sec = 0;
965 itv.it_value.tv_usec = 0;
966 setitimer(ITIMER_REAL, &itv, NULL);
969 sigaction(SIGIO, &act, NULL);
970 fcntl(rtc_fd, F_SETFL, O_ASYNC);
971 fcntl(rtc_fd, F_SETOWN, getpid());
973 #endif /* defined(__linux__) */
976 pit_min_timer_count = ((uint64_t)itv.it_interval.tv_usec *
983 void quit_timers(void)
986 timeKillEvent(timerID);
990 /***********************************************************/
991 /* character device */
993 int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
995 return s->chr_write(s, buf, len);
998 void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1003 vsnprintf(buf, sizeof(buf), fmt, ap);
1004 qemu_chr_write(s, buf, strlen(buf));
1008 void qemu_chr_send_event(CharDriverState *s, int event)
1010 if (s->chr_send_event)
1011 s->chr_send_event(s, event);
1014 void qemu_chr_add_read_handler(CharDriverState *s,
1015 IOCanRWHandler *fd_can_read,
1016 IOReadHandler *fd_read, void *opaque)
1018 s->chr_add_read_handler(s, fd_can_read, fd_read, opaque);
1021 void qemu_chr_add_event_handler(CharDriverState *s, IOEventHandler *chr_event)
1023 s->chr_event = chr_event;
1026 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1031 static void null_chr_add_read_handler(CharDriverState *chr,
1032 IOCanRWHandler *fd_can_read,
1033 IOReadHandler *fd_read, void *opaque)
1037 CharDriverState *qemu_chr_open_null(void)
1039 CharDriverState *chr;
1041 chr = qemu_mallocz(sizeof(CharDriverState));
1044 chr->chr_write = null_chr_write;
1045 chr->chr_add_read_handler = null_chr_add_read_handler;
1053 /* for nographic stdio only */
1054 IOCanRWHandler *fd_can_read;
1055 IOReadHandler *fd_read;
1059 #define STDIO_MAX_CLIENTS 2
1061 static int stdio_nb_clients;
1062 static CharDriverState *stdio_clients[STDIO_MAX_CLIENTS];
1064 static int unix_write(int fd, const uint8_t *buf, int len1)
1070 ret = write(fd, buf, len);
1072 if (errno != EINTR && errno != EAGAIN)
1074 } else if (ret == 0) {
1084 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1086 FDCharDriver *s = chr->opaque;
1087 return unix_write(s->fd_out, buf, len);
1090 static void fd_chr_add_read_handler(CharDriverState *chr,
1091 IOCanRWHandler *fd_can_read,
1092 IOReadHandler *fd_read, void *opaque)
1094 FDCharDriver *s = chr->opaque;
1096 if (nographic && s->fd_in == 0) {
1097 s->fd_can_read = fd_can_read;
1098 s->fd_read = fd_read;
1099 s->fd_opaque = opaque;
1101 qemu_add_fd_read_handler(s->fd_in, fd_can_read, fd_read, opaque);
1105 /* open a character device to a unix fd */
1106 CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
1108 CharDriverState *chr;
1111 chr = qemu_mallocz(sizeof(CharDriverState));
1114 s = qemu_mallocz(sizeof(FDCharDriver));
1122 chr->chr_write = fd_chr_write;
1123 chr->chr_add_read_handler = fd_chr_add_read_handler;
1127 /* for STDIO, we handle the case where several clients use it
1130 #define TERM_ESCAPE 0x01 /* ctrl-a is used for escape */
1132 static int term_got_escape, client_index;
1134 void term_print_help(void)
1137 "C-a h print this help\n"
1138 "C-a x exit emulator\n"
1139 "C-a s save disk data back to file (if -snapshot)\n"
1140 "C-a b send break (magic sysrq)\n"
1141 "C-a c switch between console and monitor\n"
1142 "C-a C-a send C-a\n"
1146 /* called when a char is received */
1147 static void stdio_received_byte(int ch)
1149 if (term_got_escape) {
1150 term_got_escape = 0;
1161 for (i = 0; i < MAX_DISKS; i++) {
1163 bdrv_commit(bs_table[i]);
1168 if (client_index < stdio_nb_clients) {
1169 CharDriverState *chr;
1172 chr = stdio_clients[client_index];
1174 chr->chr_event(s->fd_opaque, CHR_EVENT_BREAK);
1179 if (client_index >= stdio_nb_clients)
1181 if (client_index == 0) {
1182 /* send a new line in the monitor to get the prompt */
1190 } else if (ch == TERM_ESCAPE) {
1191 term_got_escape = 1;
1194 if (client_index < stdio_nb_clients) {
1196 CharDriverState *chr;
1199 chr = stdio_clients[client_index];
1202 /* XXX: should queue the char if the device is not
1204 if (s->fd_can_read(s->fd_opaque) > 0)
1205 s->fd_read(s->fd_opaque, buf, 1);
1210 static int stdio_can_read(void *opaque)
1212 /* XXX: not strictly correct */
1216 static void stdio_read(void *opaque, const uint8_t *buf, int size)
1219 for(i = 0; i < size; i++)
1220 stdio_received_byte(buf[i]);
1223 /* init terminal so that we can grab keys */
1224 static struct termios oldtty;
1225 static int old_fd0_flags;
1227 static void term_exit(void)
1229 tcsetattr (0, TCSANOW, &oldtty);
1230 fcntl(0, F_SETFL, old_fd0_flags);
1233 static void term_init(void)
1237 tcgetattr (0, &tty);
1239 old_fd0_flags = fcntl(0, F_GETFL);
1241 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1242 |INLCR|IGNCR|ICRNL|IXON);
1243 tty.c_oflag |= OPOST;
1244 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1245 /* if graphical mode, we allow Ctrl-C handling */
1247 tty.c_lflag &= ~ISIG;
1248 tty.c_cflag &= ~(CSIZE|PARENB);
1251 tty.c_cc[VTIME] = 0;
1253 tcsetattr (0, TCSANOW, &tty);
1257 fcntl(0, F_SETFL, O_NONBLOCK);
1260 CharDriverState *qemu_chr_open_stdio(void)
1262 CharDriverState *chr;
1265 if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
1267 chr = qemu_chr_open_fd(0, 1);
1268 if (stdio_nb_clients == 0)
1269 qemu_add_fd_read_handler(0, stdio_can_read, stdio_read, NULL);
1270 client_index = stdio_nb_clients;
1272 if (stdio_nb_clients != 0)
1274 chr = qemu_chr_open_fd(0, 1);
1276 stdio_clients[stdio_nb_clients++] = chr;
1277 if (stdio_nb_clients == 1) {
1278 /* set the terminal in raw mode */
1284 #if defined(__linux__)
1285 CharDriverState *qemu_chr_open_pty(void)
1287 char slave_name[1024];
1288 int master_fd, slave_fd;
1290 /* Not satisfying */
1291 if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
1294 fprintf(stderr, "char device redirected to %s\n", slave_name);
1295 return qemu_chr_open_fd(master_fd, master_fd);
1298 CharDriverState *qemu_chr_open_pty(void)
1304 #endif /* !defined(_WIN32) */
1306 CharDriverState *qemu_chr_open(const char *filename)
1308 if (!strcmp(filename, "vc")) {
1309 return text_console_init(&display_state);
1310 } else if (!strcmp(filename, "null")) {
1311 return qemu_chr_open_null();
1314 if (!strcmp(filename, "pty")) {
1315 return qemu_chr_open_pty();
1316 } else if (!strcmp(filename, "stdio")) {
1317 return qemu_chr_open_stdio();
1325 /***********************************************************/
1326 /* Linux network device redirectors */
1328 void hex_dump(FILE *f, const uint8_t *buf, int size)
1332 for(i=0;i<size;i+=16) {
1336 fprintf(f, "%08x ", i);
1339 fprintf(f, " %02x", buf[i+j]);
1344 for(j=0;j<len;j++) {
1346 if (c < ' ' || c > '~')
1348 fprintf(f, "%c", c);
1354 void qemu_send_packet(NetDriverState *nd, const uint8_t *buf, int size)
1356 nd->send_packet(nd, buf, size);
1359 void qemu_add_read_packet(NetDriverState *nd, IOCanRWHandler *fd_can_read,
1360 IOReadHandler *fd_read, void *opaque)
1362 nd->add_read_packet(nd, fd_can_read, fd_read, opaque);
1365 /* dummy network adapter */
1367 static void dummy_send_packet(NetDriverState *nd, const uint8_t *buf, int size)
1371 static void dummy_add_read_packet(NetDriverState *nd,
1372 IOCanRWHandler *fd_can_read,
1373 IOReadHandler *fd_read, void *opaque)
1377 static int net_dummy_init(NetDriverState *nd)
1379 nd->send_packet = dummy_send_packet;
1380 nd->add_read_packet = dummy_add_read_packet;
1381 pstrcpy(nd->ifname, sizeof(nd->ifname), "dummy");
1385 #if defined(CONFIG_SLIRP)
1387 /* slirp network adapter */
1389 static void *slirp_fd_opaque;
1390 static IOCanRWHandler *slirp_fd_can_read;
1391 static IOReadHandler *slirp_fd_read;
1392 static int slirp_inited;
1394 int slirp_can_output(void)
1396 return slirp_fd_can_read(slirp_fd_opaque);
1399 void slirp_output(const uint8_t *pkt, int pkt_len)
1402 printf("output:\n");
1403 hex_dump(stdout, pkt, pkt_len);
1405 slirp_fd_read(slirp_fd_opaque, pkt, pkt_len);
1408 static void slirp_send_packet(NetDriverState *nd, const uint8_t *buf, int size)
1412 hex_dump(stdout, buf, size);
1414 slirp_input(buf, size);
1417 static void slirp_add_read_packet(NetDriverState *nd,
1418 IOCanRWHandler *fd_can_read,
1419 IOReadHandler *fd_read, void *opaque)
1421 slirp_fd_opaque = opaque;
1422 slirp_fd_can_read = fd_can_read;
1423 slirp_fd_read = fd_read;
1426 static int net_slirp_init(NetDriverState *nd)
1428 if (!slirp_inited) {
1432 nd->send_packet = slirp_send_packet;
1433 nd->add_read_packet = slirp_add_read_packet;
1434 pstrcpy(nd->ifname, sizeof(nd->ifname), "slirp");
1438 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
1443 p1 = strchr(p, sep);
1449 if (len > buf_size - 1)
1451 memcpy(buf, p, len);
1458 static void net_slirp_redir(const char *redir_str)
1463 struct in_addr guest_addr;
1464 int host_port, guest_port;
1466 if (!slirp_inited) {
1472 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
1474 if (!strcmp(buf, "tcp")) {
1476 } else if (!strcmp(buf, "udp")) {
1482 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
1484 host_port = strtol(buf, &r, 0);
1488 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
1490 if (buf[0] == '\0') {
1491 pstrcpy(buf, sizeof(buf), "10.0.2.15");
1493 if (!inet_aton(buf, &guest_addr))
1496 guest_port = strtol(p, &r, 0);
1500 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
1501 fprintf(stderr, "qemu: could not set up redirection\n");
1506 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
1514 static void smb_exit(void)
1518 char filename[1024];
1520 /* erase all the files in the directory */
1521 d = opendir(smb_dir);
1526 if (strcmp(de->d_name, ".") != 0 &&
1527 strcmp(de->d_name, "..") != 0) {
1528 snprintf(filename, sizeof(filename), "%s/%s",
1529 smb_dir, de->d_name);
1537 /* automatic user mode samba server configuration */
1538 void net_slirp_smb(const char *exported_dir)
1540 char smb_conf[1024];
1541 char smb_cmdline[1024];
1544 if (!slirp_inited) {
1549 /* XXX: better tmp dir construction */
1550 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
1551 if (mkdir(smb_dir, 0700) < 0) {
1552 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
1555 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
1557 f = fopen(smb_conf, "w");
1559 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
1566 "socket address=127.0.0.1\n"
1567 "pid directory=%s\n"
1568 "lock directory=%s\n"
1569 "log file=%s/log.smbd\n"
1570 "smb passwd file=%s/smbpasswd\n"
1571 "security = share\n"
1586 snprintf(smb_cmdline, sizeof(smb_cmdline), "/usr/sbin/smbd -s %s",
1589 slirp_add_exec(0, smb_cmdline, 4, 139);
1592 #endif /* !defined(_WIN32) */
1594 #endif /* CONFIG_SLIRP */
1596 #if !defined(_WIN32)
1598 static int tun_open(char *ifname, int ifname_size)
1604 fd = open("/dev/tap", O_RDWR);
1606 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
1611 dev = devname(s.st_rdev, S_IFCHR);
1612 pstrcpy(ifname, ifname_size, dev);
1614 fcntl(fd, F_SETFL, O_NONBLOCK);
1618 static int tun_open(char *ifname, int ifname_size)
1623 fd = open("/dev/net/tun", O_RDWR);
1625 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
1628 memset(&ifr, 0, sizeof(ifr));
1629 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
1630 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tun%d");
1631 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
1633 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
1637 printf("Connected to host network interface: %s\n", ifr.ifr_name);
1638 pstrcpy(ifname, ifname_size, ifr.ifr_name);
1639 fcntl(fd, F_SETFL, O_NONBLOCK);
1644 static void tun_send_packet(NetDriverState *nd, const uint8_t *buf, int size)
1646 write(nd->fd, buf, size);
1649 static void tun_add_read_packet(NetDriverState *nd,
1650 IOCanRWHandler *fd_can_read,
1651 IOReadHandler *fd_read, void *opaque)
1653 qemu_add_fd_read_handler(nd->fd, fd_can_read, fd_read, opaque);
1656 static int net_tun_init(NetDriverState *nd)
1662 nd->fd = tun_open(nd->ifname, sizeof(nd->ifname));
1666 /* try to launch network init script */
1671 *parg++ = network_script;
1672 *parg++ = nd->ifname;
1674 execv(network_script, args);
1677 while (waitpid(pid, &status, 0) != pid);
1678 if (!WIFEXITED(status) ||
1679 WEXITSTATUS(status) != 0) {
1680 fprintf(stderr, "%s: could not launch network script\n",
1684 nd->send_packet = tun_send_packet;
1685 nd->add_read_packet = tun_add_read_packet;
1689 static int net_fd_init(NetDriverState *nd, int fd)
1692 nd->send_packet = tun_send_packet;
1693 nd->add_read_packet = tun_add_read_packet;
1694 pstrcpy(nd->ifname, sizeof(nd->ifname), "tunfd");
1698 #endif /* !_WIN32 */
1700 /***********************************************************/
1703 static char *pid_filename;
1705 /* Remove PID file. Called on normal exit */
1707 static void remove_pidfile(void)
1709 unlink (pid_filename);
1712 static void create_pidfile(const char *filename)
1714 struct stat pidstat;
1717 /* Try to write our PID to the named file */
1718 if (stat(filename, &pidstat) < 0) {
1719 if (errno == ENOENT) {
1720 if ((f = fopen (filename, "w")) == NULL) {
1721 perror("Opening pidfile");
1724 fprintf(f, "%d\n", getpid());
1726 pid_filename = qemu_strdup(filename);
1727 if (!pid_filename) {
1728 fprintf(stderr, "Could not save PID filename");
1731 atexit(remove_pidfile);
1734 fprintf(stderr, "%s already exists. Remove it and try again.\n",
1740 /***********************************************************/
1743 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
1747 static void dumb_resize(DisplayState *ds, int w, int h)
1751 static void dumb_refresh(DisplayState *ds)
1753 vga_update_display();
1756 void dumb_display_init(DisplayState *ds)
1761 ds->dpy_update = dumb_update;
1762 ds->dpy_resize = dumb_resize;
1763 ds->dpy_refresh = dumb_refresh;
1766 #if !defined(CONFIG_SOFTMMU)
1767 /***********************************************************/
1768 /* cpu signal handler */
1769 static void host_segv_handler(int host_signum, siginfo_t *info,
1772 if (cpu_signal_handler(host_signum, info, puc))
1774 if (stdio_nb_clients > 0)
1780 /***********************************************************/
1783 #define MAX_IO_HANDLERS 64
1785 typedef struct IOHandlerRecord {
1787 IOCanRWHandler *fd_can_read;
1788 IOReadHandler *fd_read;
1790 /* temporary data */
1793 struct IOHandlerRecord *next;
1796 static IOHandlerRecord *first_io_handler;
1798 int qemu_add_fd_read_handler(int fd, IOCanRWHandler *fd_can_read,
1799 IOReadHandler *fd_read, void *opaque)
1801 IOHandlerRecord *ioh;
1803 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
1807 ioh->fd_can_read = fd_can_read;
1808 ioh->fd_read = fd_read;
1809 ioh->opaque = opaque;
1810 ioh->next = first_io_handler;
1811 first_io_handler = ioh;
1815 void qemu_del_fd_read_handler(int fd)
1817 IOHandlerRecord **pioh, *ioh;
1819 pioh = &first_io_handler;
1824 if (ioh->fd == fd) {
1832 /***********************************************************/
1833 /* savevm/loadvm support */
1835 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
1837 fwrite(buf, 1, size, f);
1840 void qemu_put_byte(QEMUFile *f, int v)
1845 void qemu_put_be16(QEMUFile *f, unsigned int v)
1847 qemu_put_byte(f, v >> 8);
1848 qemu_put_byte(f, v);
1851 void qemu_put_be32(QEMUFile *f, unsigned int v)
1853 qemu_put_byte(f, v >> 24);
1854 qemu_put_byte(f, v >> 16);
1855 qemu_put_byte(f, v >> 8);
1856 qemu_put_byte(f, v);
1859 void qemu_put_be64(QEMUFile *f, uint64_t v)
1861 qemu_put_be32(f, v >> 32);
1862 qemu_put_be32(f, v);
1865 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size)
1867 return fread(buf, 1, size, f);
1870 int qemu_get_byte(QEMUFile *f)
1880 unsigned int qemu_get_be16(QEMUFile *f)
1883 v = qemu_get_byte(f) << 8;
1884 v |= qemu_get_byte(f);
1888 unsigned int qemu_get_be32(QEMUFile *f)
1891 v = qemu_get_byte(f) << 24;
1892 v |= qemu_get_byte(f) << 16;
1893 v |= qemu_get_byte(f) << 8;
1894 v |= qemu_get_byte(f);
1898 uint64_t qemu_get_be64(QEMUFile *f)
1901 v = (uint64_t)qemu_get_be32(f) << 32;
1902 v |= qemu_get_be32(f);
1906 int64_t qemu_ftell(QEMUFile *f)
1911 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
1913 if (fseek(f, pos, whence) < 0)
1918 typedef struct SaveStateEntry {
1922 SaveStateHandler *save_state;
1923 LoadStateHandler *load_state;
1925 struct SaveStateEntry *next;
1928 static SaveStateEntry *first_se;
1930 int register_savevm(const char *idstr,
1933 SaveStateHandler *save_state,
1934 LoadStateHandler *load_state,
1937 SaveStateEntry *se, **pse;
1939 se = qemu_malloc(sizeof(SaveStateEntry));
1942 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
1943 se->instance_id = instance_id;
1944 se->version_id = version_id;
1945 se->save_state = save_state;
1946 se->load_state = load_state;
1947 se->opaque = opaque;
1950 /* add at the end of list */
1952 while (*pse != NULL)
1953 pse = &(*pse)->next;
1958 #define QEMU_VM_FILE_MAGIC 0x5145564d
1959 #define QEMU_VM_FILE_VERSION 0x00000001
1961 int qemu_savevm(const char *filename)
1965 int len, len_pos, cur_pos, saved_vm_running, ret;
1967 saved_vm_running = vm_running;
1970 f = fopen(filename, "wb");
1976 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
1977 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
1979 for(se = first_se; se != NULL; se = se->next) {
1981 len = strlen(se->idstr);
1982 qemu_put_byte(f, len);
1983 qemu_put_buffer(f, se->idstr, len);
1985 qemu_put_be32(f, se->instance_id);
1986 qemu_put_be32(f, se->version_id);
1988 /* record size: filled later */
1990 qemu_put_be32(f, 0);
1992 se->save_state(f, se->opaque);
1994 /* fill record size */
1996 len = ftell(f) - len_pos - 4;
1997 fseek(f, len_pos, SEEK_SET);
1998 qemu_put_be32(f, len);
1999 fseek(f, cur_pos, SEEK_SET);
2005 if (saved_vm_running)
2010 static SaveStateEntry *find_se(const char *idstr, int instance_id)
2014 for(se = first_se; se != NULL; se = se->next) {
2015 if (!strcmp(se->idstr, idstr) &&
2016 instance_id == se->instance_id)
2022 int qemu_loadvm(const char *filename)
2026 int len, cur_pos, ret, instance_id, record_len, version_id;
2027 int saved_vm_running;
2031 saved_vm_running = vm_running;
2034 f = fopen(filename, "rb");
2040 v = qemu_get_be32(f);
2041 if (v != QEMU_VM_FILE_MAGIC)
2043 v = qemu_get_be32(f);
2044 if (v != QEMU_VM_FILE_VERSION) {
2051 #if defined (DO_TB_FLUSH)
2052 tb_flush(global_env);
2054 len = qemu_get_byte(f);
2057 qemu_get_buffer(f, idstr, len);
2059 instance_id = qemu_get_be32(f);
2060 version_id = qemu_get_be32(f);
2061 record_len = qemu_get_be32(f);
2063 printf("idstr=%s instance=0x%x version=%d len=%d\n",
2064 idstr, instance_id, version_id, record_len);
2067 se = find_se(idstr, instance_id);
2069 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
2070 instance_id, idstr);
2072 ret = se->load_state(f, se->opaque, version_id);
2074 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
2075 instance_id, idstr);
2078 /* always seek to exact end of record */
2079 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
2084 if (saved_vm_running)
2089 /***********************************************************/
2090 /* cpu save/restore */
2092 #if defined(TARGET_I386)
2094 static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
2096 qemu_put_be32(f, dt->selector);
2097 qemu_put_betl(f, dt->base);
2098 qemu_put_be32(f, dt->limit);
2099 qemu_put_be32(f, dt->flags);
2102 static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
2104 dt->selector = qemu_get_be32(f);
2105 dt->base = qemu_get_betl(f);
2106 dt->limit = qemu_get_be32(f);
2107 dt->flags = qemu_get_be32(f);
2110 void cpu_save(QEMUFile *f, void *opaque)
2112 CPUState *env = opaque;
2113 uint16_t fptag, fpus, fpuc, fpregs_format;
2117 for(i = 0; i < CPU_NB_REGS; i++)
2118 qemu_put_betls(f, &env->regs[i]);
2119 qemu_put_betls(f, &env->eip);
2120 qemu_put_betls(f, &env->eflags);
2121 hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
2122 qemu_put_be32s(f, &hflags);
2126 fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
2128 for(i = 0; i < 8; i++) {
2129 fptag |= ((!env->fptags[i]) << i);
2132 qemu_put_be16s(f, &fpuc);
2133 qemu_put_be16s(f, &fpus);
2134 qemu_put_be16s(f, &fptag);
2136 #ifdef USE_X86LDOUBLE
2141 qemu_put_be16s(f, &fpregs_format);
2143 for(i = 0; i < 8; i++) {
2144 #ifdef USE_X86LDOUBLE
2148 /* we save the real CPU data (in case of MMX usage only 'mant'
2149 contains the MMX register */
2150 cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
2151 qemu_put_be64(f, mant);
2152 qemu_put_be16(f, exp);
2155 /* if we use doubles for float emulation, we save the doubles to
2156 avoid losing information in case of MMX usage. It can give
2157 problems if the image is restored on a CPU where long
2158 doubles are used instead. */
2159 qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
2163 for(i = 0; i < 6; i++)
2164 cpu_put_seg(f, &env->segs[i]);
2165 cpu_put_seg(f, &env->ldt);
2166 cpu_put_seg(f, &env->tr);
2167 cpu_put_seg(f, &env->gdt);
2168 cpu_put_seg(f, &env->idt);
2170 qemu_put_be32s(f, &env->sysenter_cs);
2171 qemu_put_be32s(f, &env->sysenter_esp);
2172 qemu_put_be32s(f, &env->sysenter_eip);
2174 qemu_put_betls(f, &env->cr[0]);
2175 qemu_put_betls(f, &env->cr[2]);
2176 qemu_put_betls(f, &env->cr[3]);
2177 qemu_put_betls(f, &env->cr[4]);
2179 for(i = 0; i < 8; i++)
2180 qemu_put_betls(f, &env->dr[i]);
2183 qemu_put_be32s(f, &env->a20_mask);
2186 qemu_put_be32s(f, &env->mxcsr);
2187 for(i = 0; i < CPU_NB_REGS; i++) {
2188 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
2189 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
2192 #ifdef TARGET_X86_64
2193 qemu_put_be64s(f, &env->efer);
2194 qemu_put_be64s(f, &env->star);
2195 qemu_put_be64s(f, &env->lstar);
2196 qemu_put_be64s(f, &env->cstar);
2197 qemu_put_be64s(f, &env->fmask);
2198 qemu_put_be64s(f, &env->kernelgsbase);
2202 #ifdef USE_X86LDOUBLE
2203 /* XXX: add that in a FPU generic layer */
2204 union x86_longdouble {
2209 #define MANTD1(fp) (fp & ((1LL << 52) - 1))
2210 #define EXPBIAS1 1023
2211 #define EXPD1(fp) ((fp >> 52) & 0x7FF)
2212 #define SIGND1(fp) ((fp >> 32) & 0x80000000)
2214 static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
2218 p->mant = (MANTD1(temp) << 11) | (1LL << 63);
2219 /* exponent + sign */
2220 e = EXPD1(temp) - EXPBIAS1 + 16383;
2221 e |= SIGND1(temp) >> 16;
2226 int cpu_load(QEMUFile *f, void *opaque, int version_id)
2228 CPUState *env = opaque;
2231 uint16_t fpus, fpuc, fptag, fpregs_format;
2233 if (version_id != 3)
2235 for(i = 0; i < CPU_NB_REGS; i++)
2236 qemu_get_betls(f, &env->regs[i]);
2237 qemu_get_betls(f, &env->eip);
2238 qemu_get_betls(f, &env->eflags);
2239 qemu_get_be32s(f, &hflags);
2241 qemu_get_be16s(f, &fpuc);
2242 qemu_get_be16s(f, &fpus);
2243 qemu_get_be16s(f, &fptag);
2244 qemu_get_be16s(f, &fpregs_format);
2246 /* NOTE: we cannot always restore the FPU state if the image come
2247 from a host with a different 'USE_X86LDOUBLE' define. We guess
2248 if we are in an MMX state to restore correctly in that case. */
2249 guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
2250 for(i = 0; i < 8; i++) {
2254 switch(fpregs_format) {
2256 mant = qemu_get_be64(f);
2257 exp = qemu_get_be16(f);
2258 #ifdef USE_X86LDOUBLE
2259 env->fpregs[i].d = cpu_set_fp80(mant, exp);
2261 /* difficult case */
2263 env->fpregs[i].mmx.MMX_Q(0) = mant;
2265 env->fpregs[i].d = cpu_set_fp80(mant, exp);
2269 mant = qemu_get_be64(f);
2270 #ifdef USE_X86LDOUBLE
2272 union x86_longdouble *p;
2273 /* difficult case */
2274 p = (void *)&env->fpregs[i];
2279 fp64_to_fp80(p, mant);
2283 env->fpregs[i].mmx.MMX_Q(0) = mant;
2292 /* XXX: restore FPU round state */
2293 env->fpstt = (fpus >> 11) & 7;
2294 env->fpus = fpus & ~0x3800;
2296 for(i = 0; i < 8; i++) {
2297 env->fptags[i] = (fptag >> i) & 1;
2300 for(i = 0; i < 6; i++)
2301 cpu_get_seg(f, &env->segs[i]);
2302 cpu_get_seg(f, &env->ldt);
2303 cpu_get_seg(f, &env->tr);
2304 cpu_get_seg(f, &env->gdt);
2305 cpu_get_seg(f, &env->idt);
2307 qemu_get_be32s(f, &env->sysenter_cs);
2308 qemu_get_be32s(f, &env->sysenter_esp);
2309 qemu_get_be32s(f, &env->sysenter_eip);
2311 qemu_get_betls(f, &env->cr[0]);
2312 qemu_get_betls(f, &env->cr[2]);
2313 qemu_get_betls(f, &env->cr[3]);
2314 qemu_get_betls(f, &env->cr[4]);
2316 for(i = 0; i < 8; i++)
2317 qemu_get_betls(f, &env->dr[i]);
2320 qemu_get_be32s(f, &env->a20_mask);
2322 qemu_get_be32s(f, &env->mxcsr);
2323 for(i = 0; i < CPU_NB_REGS; i++) {
2324 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
2325 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
2328 #ifdef TARGET_X86_64
2329 qemu_get_be64s(f, &env->efer);
2330 qemu_get_be64s(f, &env->star);
2331 qemu_get_be64s(f, &env->lstar);
2332 qemu_get_be64s(f, &env->cstar);
2333 qemu_get_be64s(f, &env->fmask);
2334 qemu_get_be64s(f, &env->kernelgsbase);
2337 /* XXX: compute hflags from scratch, except for CPL and IIF */
2338 env->hflags = hflags;
2343 #elif defined(TARGET_PPC)
2344 void cpu_save(QEMUFile *f, void *opaque)
2348 int cpu_load(QEMUFile *f, void *opaque, int version_id)
2353 #elif defined(TARGET_MIPS)
2354 void cpu_save(QEMUFile *f, void *opaque)
2358 int cpu_load(QEMUFile *f, void *opaque, int version_id)
2363 #elif defined(TARGET_SPARC)
2364 void cpu_save(QEMUFile *f, void *opaque)
2366 CPUState *env = opaque;
2370 for(i = 0; i < 8; i++)
2371 qemu_put_betls(f, &env->gregs[i]);
2372 for(i = 0; i < NWINDOWS * 16; i++)
2373 qemu_put_betls(f, &env->regbase[i]);
2376 for(i = 0; i < TARGET_FPREGS; i++) {
2382 qemu_put_betl(f, u.i);
2385 qemu_put_betls(f, &env->pc);
2386 qemu_put_betls(f, &env->npc);
2387 qemu_put_betls(f, &env->y);
2389 qemu_put_be32(f, tmp);
2390 qemu_put_betls(f, &env->fsr);
2391 qemu_put_betls(f, &env->tbr);
2392 #ifndef TARGET_SPARC64
2393 qemu_put_be32s(f, &env->wim);
2395 for(i = 0; i < 16; i++)
2396 qemu_put_be32s(f, &env->mmuregs[i]);
2400 int cpu_load(QEMUFile *f, void *opaque, int version_id)
2402 CPUState *env = opaque;
2406 for(i = 0; i < 8; i++)
2407 qemu_get_betls(f, &env->gregs[i]);
2408 for(i = 0; i < NWINDOWS * 16; i++)
2409 qemu_get_betls(f, &env->regbase[i]);
2412 for(i = 0; i < TARGET_FPREGS; i++) {
2417 u.i = qemu_get_betl(f);
2421 qemu_get_betls(f, &env->pc);
2422 qemu_get_betls(f, &env->npc);
2423 qemu_get_betls(f, &env->y);
2424 tmp = qemu_get_be32(f);
2425 env->cwp = 0; /* needed to ensure that the wrapping registers are
2426 correctly updated */
2428 qemu_get_betls(f, &env->fsr);
2429 qemu_get_betls(f, &env->tbr);
2430 #ifndef TARGET_SPARC64
2431 qemu_get_be32s(f, &env->wim);
2433 for(i = 0; i < 16; i++)
2434 qemu_get_be32s(f, &env->mmuregs[i]);
2441 #warning No CPU save/restore functions
2445 /***********************************************************/
2446 /* ram save/restore */
2448 /* we just avoid storing empty pages */
2449 static void ram_put_page(QEMUFile *f, const uint8_t *buf, int len)
2454 for(i = 1; i < len; i++) {
2458 qemu_put_byte(f, 1);
2459 qemu_put_byte(f, v);
2462 qemu_put_byte(f, 0);
2463 qemu_put_buffer(f, buf, len);
2466 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
2470 v = qemu_get_byte(f);
2473 if (qemu_get_buffer(f, buf, len) != len)
2477 v = qemu_get_byte(f);
2478 memset(buf, v, len);
2486 static void ram_save(QEMUFile *f, void *opaque)
2489 qemu_put_be32(f, phys_ram_size);
2490 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
2491 ram_put_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
2495 static int ram_load(QEMUFile *f, void *opaque, int version_id)
2499 if (version_id != 1)
2501 if (qemu_get_be32(f) != phys_ram_size)
2503 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
2504 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
2511 /***********************************************************/
2512 /* machine registration */
2514 QEMUMachine *first_machine = NULL;
2516 int qemu_register_machine(QEMUMachine *m)
2519 pm = &first_machine;
2527 QEMUMachine *find_machine(const char *name)
2531 for(m = first_machine; m != NULL; m = m->next) {
2532 if (!strcmp(m->name, name))
2538 /***********************************************************/
2539 /* main execution loop */
2541 void gui_update(void *opaque)
2543 display_state.dpy_refresh(&display_state);
2544 qemu_mod_timer(gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
2547 /* XXX: support several handlers */
2548 VMStopHandler *vm_stop_cb;
2549 VMStopHandler *vm_stop_opaque;
2551 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
2554 vm_stop_opaque = opaque;
2558 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
2571 void vm_stop(int reason)
2574 cpu_disable_ticks();
2578 vm_stop_cb(vm_stop_opaque, reason);
2584 /* reset/shutdown handler */
2586 typedef struct QEMUResetEntry {
2587 QEMUResetHandler *func;
2589 struct QEMUResetEntry *next;
2592 static QEMUResetEntry *first_reset_entry;
2593 static int reset_requested;
2594 static int shutdown_requested;
2595 static int powerdown_requested;
2597 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
2599 QEMUResetEntry **pre, *re;
2601 pre = &first_reset_entry;
2602 while (*pre != NULL)
2603 pre = &(*pre)->next;
2604 re = qemu_mallocz(sizeof(QEMUResetEntry));
2606 re->opaque = opaque;
2611 void qemu_system_reset(void)
2615 /* reset all devices */
2616 for(re = first_reset_entry; re != NULL; re = re->next) {
2617 re->func(re->opaque);
2621 void qemu_system_reset_request(void)
2623 reset_requested = 1;
2624 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
2627 void qemu_system_shutdown_request(void)
2629 shutdown_requested = 1;
2630 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
2633 void qemu_system_powerdown_request(void)
2635 powerdown_requested = 1;
2636 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
2639 static void main_cpu_reset(void *opaque)
2641 #if defined(TARGET_I386) || defined(TARGET_SPARC)
2642 CPUState *env = opaque;
2647 void main_loop_wait(int timeout)
2650 struct pollfd ufds[MAX_IO_HANDLERS + 1], *pf;
2651 IOHandlerRecord *ioh, *ioh_next;
2661 /* poll any events */
2662 /* XXX: separate device handlers from system ones */
2664 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2665 if (!ioh->fd_can_read) {
2668 pf->events = POLLIN;
2672 max_size = ioh->fd_can_read(ioh->opaque);
2674 if (max_size > sizeof(buf))
2675 max_size = sizeof(buf);
2677 pf->events = POLLIN;
2684 ioh->max_size = max_size;
2687 ret = poll(ufds, pf - ufds, timeout);
2689 /* XXX: better handling of removal */
2690 for(ioh = first_io_handler; ioh != NULL; ioh = ioh_next) {
2691 ioh_next = ioh->next;
2694 if (pf->revents & POLLIN) {
2695 if (ioh->max_size == 0) {
2696 /* just a read event */
2697 ioh->fd_read(ioh->opaque, NULL, 0);
2699 n = read(ioh->fd, buf, ioh->max_size);
2701 ioh->fd_read(ioh->opaque, buf, n);
2702 } else if (errno != EAGAIN) {
2703 ioh->fd_read(ioh->opaque, NULL, -errno);
2710 #endif /* !defined(_WIN32) */
2711 #if defined(CONFIG_SLIRP)
2712 /* XXX: merge with poll() */
2714 fd_set rfds, wfds, xfds;
2722 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
2725 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
2727 slirp_select_poll(&rfds, &wfds, &xfds);
2733 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
2734 qemu_get_clock(vm_clock));
2735 /* run dma transfers, if any */
2739 /* real time timers */
2740 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
2741 qemu_get_clock(rt_clock));
2747 CPUState *env = global_env;
2751 ret = cpu_exec(env);
2752 if (shutdown_requested) {
2753 ret = EXCP_INTERRUPT;
2756 if (reset_requested) {
2757 reset_requested = 0;
2758 qemu_system_reset();
2759 ret = EXCP_INTERRUPT;
2761 if (powerdown_requested) {
2762 powerdown_requested = 0;
2763 qemu_system_powerdown();
2764 ret = EXCP_INTERRUPT;
2766 if (ret == EXCP_DEBUG) {
2767 vm_stop(EXCP_DEBUG);
2769 /* if hlt instruction, we wait until the next IRQ */
2770 /* XXX: use timeout computed from timers */
2771 if (ret == EXCP_HLT)
2778 main_loop_wait(timeout);
2780 cpu_disable_ticks();
2786 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2004 Fabrice Bellard\n"
2787 "usage: %s [options] [disk_image]\n"
2789 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
2791 "Standard options:\n"
2792 "-M machine select emulated machine (-M ? for list)\n"
2793 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
2794 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
2795 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
2796 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
2797 "-boot [a|c|d] boot on floppy (a), hard disk (c) or CD-ROM (d)\n"
2798 "-snapshot write to temporary files instead of disk image files\n"
2799 "-m megs set virtual RAM size to megs MB [default=%d]\n"
2800 "-nographic disable graphical output and redirect serial I/Os to console\n"
2802 "-k language use keyboard layout (for example \"fr\" for French)\n"
2804 "-enable-audio enable audio support\n"
2805 "-localtime set the real time clock to local time [default=utc]\n"
2806 "-full-screen start in full screen\n"
2808 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
2810 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
2811 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
2814 "Network options:\n"
2815 "-nics n simulate 'n' network cards [default=1]\n"
2816 "-macaddr addr set the mac address of the first interface\n"
2817 "-n script set tap/tun network init script [default=%s]\n"
2818 "-tun-fd fd use this fd as already opened tap/tun interface\n"
2820 "-user-net use user mode network stack [default if no tap/tun script]\n"
2821 "-tftp prefix allow tftp access to files starting with prefix [-user-net]\n"
2823 "-smb dir allow SMB access to files in 'dir' [-user-net]\n"
2825 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
2826 " redirect TCP or UDP connections from host to guest [-user-net]\n"
2828 "-dummy-net use dummy network stack\n"
2830 "Linux boot specific:\n"
2831 "-kernel bzImage use 'bzImage' as kernel image\n"
2832 "-append cmdline use 'cmdline' as kernel command line\n"
2833 "-initrd file use 'file' as initial ram disk\n"
2835 "Debug/Expert options:\n"
2836 "-monitor dev redirect the monitor to char device 'dev'\n"
2837 "-serial dev redirect the serial port to char device 'dev'\n"
2838 "-parallel dev redirect the parallel port to char device 'dev'\n"
2839 "-pidfile file Write PID to 'file'\n"
2840 "-S freeze CPU at startup (use 'c' to start execution)\n"
2841 "-s wait gdb connection to port %d\n"
2842 "-p port change gdb connection port\n"
2843 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
2844 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
2845 " translation (t=none or lba) (usually qemu can guess them)\n"
2846 "-L path set the directory for the BIOS and VGA BIOS\n"
2848 "-no-kqemu disable KQEMU kernel module usage\n"
2850 #ifdef USE_CODE_COPY
2851 "-no-code-copy disable code copy acceleration\n"
2854 "-isa simulate an ISA-only system (default is PCI system)\n"
2855 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
2856 " (default is CL-GD5446 PCI VGA)\n"
2858 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
2860 "During emulation, the following keys are useful:\n"
2861 "ctrl-alt-f toggle full screen\n"
2862 "ctrl-alt-n switch to virtual console 'n'\n"
2863 "ctrl-alt toggle mouse and keyboard grab\n"
2865 "When using -nographic, press 'ctrl-a h' to get some help.\n"
2867 #ifdef CONFIG_SOFTMMU
2873 DEFAULT_NETWORK_SCRIPT,
2874 DEFAULT_GDBSTUB_PORT,
2876 #ifndef CONFIG_SOFTMMU
2878 "NOTE: this version of QEMU is faster but it needs slightly patched OSes to\n"
2879 "work. Please use the 'qemu' executable to have a more accurate (but slower)\n"
2885 #define HAS_ARG 0x0001
2899 QEMU_OPTION_snapshot,
2901 QEMU_OPTION_nographic,
2902 QEMU_OPTION_enable_audio,
2905 QEMU_OPTION_macaddr,
2908 QEMU_OPTION_user_net,
2912 QEMU_OPTION_dummy_net,
2924 QEMU_OPTION_no_code_copy,
2929 QEMU_OPTION_localtime,
2930 QEMU_OPTION_cirrusvga,
2932 QEMU_OPTION_std_vga,
2933 QEMU_OPTION_monitor,
2935 QEMU_OPTION_parallel,
2937 QEMU_OPTION_full_screen,
2938 QEMU_OPTION_pidfile,
2939 QEMU_OPTION_no_kqemu,
2940 QEMU_OPTION_win2k_hack,
2943 typedef struct QEMUOption {
2949 const QEMUOption qemu_options[] = {
2950 { "h", 0, QEMU_OPTION_h },
2952 { "M", HAS_ARG, QEMU_OPTION_M },
2953 { "fda", HAS_ARG, QEMU_OPTION_fda },
2954 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
2955 { "hda", HAS_ARG, QEMU_OPTION_hda },
2956 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
2957 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
2958 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
2959 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
2960 { "boot", HAS_ARG, QEMU_OPTION_boot },
2961 { "snapshot", 0, QEMU_OPTION_snapshot },
2962 { "m", HAS_ARG, QEMU_OPTION_m },
2963 { "nographic", 0, QEMU_OPTION_nographic },
2964 { "k", HAS_ARG, QEMU_OPTION_k },
2965 { "enable-audio", 0, QEMU_OPTION_enable_audio },
2967 { "nics", HAS_ARG, QEMU_OPTION_nics},
2968 { "macaddr", HAS_ARG, QEMU_OPTION_macaddr},
2969 { "n", HAS_ARG, QEMU_OPTION_n },
2970 { "tun-fd", HAS_ARG, QEMU_OPTION_tun_fd },
2972 { "user-net", 0, QEMU_OPTION_user_net },
2973 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
2975 { "smb", HAS_ARG, QEMU_OPTION_smb },
2977 { "redir", HAS_ARG, QEMU_OPTION_redir },
2979 { "dummy-net", 0, QEMU_OPTION_dummy_net },
2981 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
2982 { "append", HAS_ARG, QEMU_OPTION_append },
2983 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
2985 { "S", 0, QEMU_OPTION_S },
2986 { "s", 0, QEMU_OPTION_s },
2987 { "p", HAS_ARG, QEMU_OPTION_p },
2988 { "d", HAS_ARG, QEMU_OPTION_d },
2989 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
2990 { "L", HAS_ARG, QEMU_OPTION_L },
2991 { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
2993 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
2996 { "prep", 0, QEMU_OPTION_prep },
2998 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
2999 { "g", 1, QEMU_OPTION_g },
3001 { "localtime", 0, QEMU_OPTION_localtime },
3002 { "isa", 0, QEMU_OPTION_isa },
3003 { "std-vga", 0, QEMU_OPTION_std_vga },
3004 { "monitor", 1, QEMU_OPTION_monitor },
3005 { "serial", 1, QEMU_OPTION_serial },
3006 { "parallel", 1, QEMU_OPTION_parallel },
3007 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
3008 { "full-screen", 0, QEMU_OPTION_full_screen },
3009 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
3010 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
3012 /* temporary options */
3013 { "pci", 0, QEMU_OPTION_pci },
3014 { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
3018 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
3020 /* this stack is only used during signal handling */
3021 #define SIGNAL_STACK_SIZE 32768
3023 static uint8_t *signal_stack;
3027 /* password input */
3029 static BlockDriverState *get_bdrv(int index)
3031 BlockDriverState *bs;
3034 bs = bs_table[index];
3035 } else if (index < 6) {
3036 bs = fd_table[index - 4];
3043 static void read_passwords(void)
3045 BlockDriverState *bs;
3049 for(i = 0; i < 6; i++) {
3051 if (bs && bdrv_is_encrypted(bs)) {
3052 term_printf("%s is encrypted.\n", bdrv_get_device_name(bs));
3053 for(j = 0; j < 3; j++) {
3054 monitor_readline("Password: ",
3055 1, password, sizeof(password));
3056 if (bdrv_set_key(bs, password) == 0)
3058 term_printf("invalid password\n");
3064 /* XXX: currently we cannot use simultaneously different CPUs */
3065 void register_machines(void)
3067 #if defined(TARGET_I386)
3068 qemu_register_machine(&pc_machine);
3069 #elif defined(TARGET_PPC)
3070 qemu_register_machine(&heathrow_machine);
3071 qemu_register_machine(&core99_machine);
3072 qemu_register_machine(&prep_machine);
3073 #elif defined(TARGET_MIPS)
3074 qemu_register_machine(&mips_machine);
3075 #elif defined(TARGET_SPARC)
3076 #ifdef TARGET_SPARC64
3077 qemu_register_machine(&sun4u_machine);
3079 qemu_register_machine(&sun4m_machine);
3084 #define NET_IF_TUN 0
3085 #define NET_IF_USER 1
3086 #define NET_IF_DUMMY 2
3088 int main(int argc, char **argv)
3090 #ifdef CONFIG_GDBSTUB
3091 int use_gdbstub, gdbstub_port;
3094 int snapshot, linux_boot;
3096 const char *initrd_filename;
3097 const char *hd_filename[MAX_DISKS], *fd_filename[MAX_FD];
3098 const char *kernel_filename, *kernel_cmdline;
3099 DisplayState *ds = &display_state;
3100 int cyls, heads, secs, translation;
3101 int start_emulation = 1;
3103 int net_if_type, nb_tun_fds, tun_fds[MAX_NICS];
3105 const char *r, *optarg;
3106 CharDriverState *monitor_hd;
3107 char monitor_device[128];
3108 char serial_devices[MAX_SERIAL_PORTS][128];
3109 int serial_device_index;
3110 char parallel_devices[MAX_PARALLEL_PORTS][128];
3111 int parallel_device_index;
3112 const char *loadvm = NULL;
3113 QEMUMachine *machine;
3115 #if !defined(CONFIG_SOFTMMU)
3116 /* we never want that malloc() uses mmap() */
3117 mallopt(M_MMAP_THRESHOLD, 4096 * 1024);
3119 register_machines();
3120 machine = first_machine;
3121 initrd_filename = NULL;
3122 for(i = 0; i < MAX_FD; i++)
3123 fd_filename[i] = NULL;
3124 for(i = 0; i < MAX_DISKS; i++)
3125 hd_filename[i] = NULL;
3126 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
3127 vga_ram_size = VGA_RAM_SIZE;
3128 bios_size = BIOS_SIZE;
3129 pstrcpy(network_script, sizeof(network_script), DEFAULT_NETWORK_SCRIPT);
3130 #ifdef CONFIG_GDBSTUB
3132 gdbstub_port = DEFAULT_GDBSTUB_PORT;
3136 kernel_filename = NULL;
3137 kernel_cmdline = "";
3143 cyls = heads = secs = 0;
3144 translation = BIOS_ATA_TRANSLATION_AUTO;
3145 pstrcpy(monitor_device, sizeof(monitor_device), "vc");
3147 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
3148 for(i = 1; i < MAX_SERIAL_PORTS; i++)
3149 serial_devices[i][0] = '\0';
3150 serial_device_index = 0;
3152 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
3153 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
3154 parallel_devices[i][0] = '\0';
3155 parallel_device_index = 0;
3160 /* default mac address of the first network interface */
3174 hd_filename[0] = argv[optind++];
3176 const QEMUOption *popt;
3179 popt = qemu_options;
3182 fprintf(stderr, "%s: invalid option -- '%s'\n",
3186 if (!strcmp(popt->name, r + 1))
3190 if (popt->flags & HAS_ARG) {
3191 if (optind >= argc) {
3192 fprintf(stderr, "%s: option '%s' requires an argument\n",
3196 optarg = argv[optind++];
3201 switch(popt->index) {
3203 machine = find_machine(optarg);
3206 printf("Supported machines are:\n");
3207 for(m = first_machine; m != NULL; m = m->next) {
3208 printf("%-10s %s%s\n",
3210 m == first_machine ? " (default)" : "");
3215 case QEMU_OPTION_initrd:
3216 initrd_filename = optarg;
3218 case QEMU_OPTION_hda:
3219 case QEMU_OPTION_hdb:
3220 case QEMU_OPTION_hdc:
3221 case QEMU_OPTION_hdd:
3224 hd_index = popt->index - QEMU_OPTION_hda;
3225 hd_filename[hd_index] = optarg;
3226 if (hd_index == cdrom_index)
3230 case QEMU_OPTION_snapshot:
3233 case QEMU_OPTION_hdachs:
3237 cyls = strtol(p, (char **)&p, 0);
3238 if (cyls < 1 || cyls > 16383)
3243 heads = strtol(p, (char **)&p, 0);
3244 if (heads < 1 || heads > 16)
3249 secs = strtol(p, (char **)&p, 0);
3250 if (secs < 1 || secs > 63)
3254 if (!strcmp(p, "none"))
3255 translation = BIOS_ATA_TRANSLATION_NONE;
3256 else if (!strcmp(p, "lba"))
3257 translation = BIOS_ATA_TRANSLATION_LBA;
3258 else if (!strcmp(p, "auto"))
3259 translation = BIOS_ATA_TRANSLATION_AUTO;
3262 } else if (*p != '\0') {
3264 fprintf(stderr, "qemu: invalid physical CHS format\n");
3269 case QEMU_OPTION_nographic:
3270 pstrcpy(monitor_device, sizeof(monitor_device), "stdio");
3271 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "stdio");
3274 case QEMU_OPTION_kernel:
3275 kernel_filename = optarg;
3277 case QEMU_OPTION_append:
3278 kernel_cmdline = optarg;
3280 case QEMU_OPTION_tun_fd:
3284 net_if_type = NET_IF_TUN;
3285 if (nb_tun_fds < MAX_NICS) {
3286 fd = strtol(optarg, (char **)&p, 0);
3288 fprintf(stderr, "qemu: invalid fd for network interface %d\n", nb_tun_fds);
3291 tun_fds[nb_tun_fds++] = fd;
3295 case QEMU_OPTION_cdrom:
3296 if (cdrom_index >= 0) {
3297 hd_filename[cdrom_index] = optarg;
3300 case QEMU_OPTION_boot:
3301 boot_device = optarg[0];
3302 if (boot_device != 'a' &&
3305 boot_device != 'n' &&
3307 boot_device != 'c' && boot_device != 'd') {
3308 fprintf(stderr, "qemu: invalid boot device '%c'\n", boot_device);
3312 case QEMU_OPTION_fda:
3313 fd_filename[0] = optarg;
3315 case QEMU_OPTION_fdb:
3316 fd_filename[1] = optarg;
3318 case QEMU_OPTION_no_code_copy:
3319 code_copy_enabled = 0;
3321 case QEMU_OPTION_nics:
3322 nb_nics = atoi(optarg);
3323 if (nb_nics < 0 || nb_nics > MAX_NICS) {
3324 fprintf(stderr, "qemu: invalid number of network interfaces\n");
3328 case QEMU_OPTION_macaddr:
3333 for(i = 0; i < 6; i++) {
3334 macaddr[i] = strtol(p, (char **)&p, 16);
3341 fprintf(stderr, "qemu: invalid syntax for ethernet address\n");
3350 case QEMU_OPTION_tftp:
3351 tftp_prefix = optarg;
3354 case QEMU_OPTION_smb:
3355 net_slirp_smb(optarg);
3358 case QEMU_OPTION_user_net:
3359 net_if_type = NET_IF_USER;
3361 case QEMU_OPTION_redir:
3362 net_slirp_redir(optarg);
3365 case QEMU_OPTION_dummy_net:
3366 net_if_type = NET_IF_DUMMY;
3368 case QEMU_OPTION_enable_audio:
3375 ram_size = atoi(optarg) * 1024 * 1024;
3378 if (ram_size > PHYS_RAM_MAX_SIZE) {
3379 fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
3380 PHYS_RAM_MAX_SIZE / (1024 * 1024));
3389 mask = cpu_str_to_log_mask(optarg);
3391 printf("Log items (comma separated):\n");
3392 for(item = cpu_log_items; item->mask != 0; item++) {
3393 printf("%-10s %s\n", item->name, item->help);
3401 pstrcpy(network_script, sizeof(network_script), optarg);
3403 #ifdef CONFIG_GDBSTUB
3408 gdbstub_port = atoi(optarg);
3415 start_emulation = 0;
3417 case QEMU_OPTION_pci:
3420 case QEMU_OPTION_isa:
3423 case QEMU_OPTION_prep:
3427 keyboard_layout = optarg;
3429 case QEMU_OPTION_localtime:
3432 case QEMU_OPTION_cirrusvga:
3433 cirrus_vga_enabled = 1;
3435 case QEMU_OPTION_std_vga:
3436 cirrus_vga_enabled = 0;
3443 w = strtol(p, (char **)&p, 10);
3446 fprintf(stderr, "qemu: invalid resolution or depth\n");
3452 h = strtol(p, (char **)&p, 10);
3457 depth = strtol(p, (char **)&p, 10);
3458 if (depth != 8 && depth != 15 && depth != 16 &&
3459 depth != 24 && depth != 32)
3461 } else if (*p == '\0') {
3462 depth = graphic_depth;
3469 graphic_depth = depth;
3472 case QEMU_OPTION_monitor:
3473 pstrcpy(monitor_device, sizeof(monitor_device), optarg);
3475 case QEMU_OPTION_serial:
3476 if (serial_device_index >= MAX_SERIAL_PORTS) {
3477 fprintf(stderr, "qemu: too many serial ports\n");
3480 pstrcpy(serial_devices[serial_device_index],
3481 sizeof(serial_devices[0]), optarg);
3482 serial_device_index++;
3484 case QEMU_OPTION_parallel:
3485 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
3486 fprintf(stderr, "qemu: too many parallel ports\n");
3489 pstrcpy(parallel_devices[parallel_device_index],
3490 sizeof(parallel_devices[0]), optarg);
3491 parallel_device_index++;
3493 case QEMU_OPTION_loadvm:
3496 case QEMU_OPTION_full_screen:
3499 case QEMU_OPTION_pidfile:
3500 create_pidfile(optarg);
3503 case QEMU_OPTION_win2k_hack:
3504 win2k_install_hack = 1;
3508 case QEMU_OPTION_no_kqemu:
3516 linux_boot = (kernel_filename != NULL);
3519 hd_filename[0] == '\0' &&
3520 (cdrom_index >= 0 && hd_filename[cdrom_index] == '\0') &&
3521 fd_filename[0] == '\0')
3524 /* boot to cd by default if no hard disk */
3525 if (hd_filename[0] == '\0' && boot_device == 'c') {
3526 if (fd_filename[0] != '\0')
3532 #if !defined(CONFIG_SOFTMMU)
3533 /* must avoid mmap() usage of glibc by setting a buffer "by hand" */
3535 static uint8_t stdout_buf[4096];
3536 setvbuf(stdout, stdout_buf, _IOLBF, sizeof(stdout_buf));
3539 setvbuf(stdout, NULL, _IOLBF, 0);
3542 /* init host network redirectors */
3543 if (net_if_type == -1) {
3544 net_if_type = NET_IF_TUN;
3545 #if defined(CONFIG_SLIRP)
3546 if (access(network_script, R_OK) < 0) {
3547 net_if_type = NET_IF_USER;
3552 for(i = 0; i < nb_nics; i++) {
3553 NetDriverState *nd = &nd_table[i];
3555 /* init virtual mac address */
3556 nd->macaddr[0] = macaddr[0];
3557 nd->macaddr[1] = macaddr[1];
3558 nd->macaddr[2] = macaddr[2];
3559 nd->macaddr[3] = macaddr[3];
3560 nd->macaddr[4] = macaddr[4];
3561 nd->macaddr[5] = macaddr[5] + i;
3562 switch(net_if_type) {
3563 #if defined(CONFIG_SLIRP)
3568 #if !defined(_WIN32)
3570 if (i < nb_tun_fds) {
3571 net_fd_init(nd, tun_fds[i]);
3573 if (net_tun_init(nd) < 0)
3585 /* init the memory */
3586 phys_ram_size = ram_size + vga_ram_size + bios_size;
3588 #ifdef CONFIG_SOFTMMU
3589 phys_ram_base = qemu_vmalloc(phys_ram_size);
3590 if (!phys_ram_base) {
3591 fprintf(stderr, "Could not allocate physical memory\n");
3595 /* as we must map the same page at several addresses, we must use
3600 tmpdir = getenv("QEMU_TMPDIR");
3603 snprintf(phys_ram_file, sizeof(phys_ram_file), "%s/vlXXXXXX", tmpdir);
3604 if (mkstemp(phys_ram_file) < 0) {
3605 fprintf(stderr, "Could not create temporary memory file '%s'\n",
3609 phys_ram_fd = open(phys_ram_file, O_CREAT | O_TRUNC | O_RDWR, 0600);
3610 if (phys_ram_fd < 0) {
3611 fprintf(stderr, "Could not open temporary memory file '%s'\n",
3615 ftruncate(phys_ram_fd, phys_ram_size);
3616 unlink(phys_ram_file);
3617 phys_ram_base = mmap(get_mmap_addr(phys_ram_size),
3619 PROT_WRITE | PROT_READ, MAP_SHARED | MAP_FIXED,
3621 if (phys_ram_base == MAP_FAILED) {
3622 fprintf(stderr, "Could not map physical memory\n");
3628 /* we always create the cdrom drive, even if no disk is there */
3630 if (cdrom_index >= 0) {
3631 bs_table[cdrom_index] = bdrv_new("cdrom");
3632 bdrv_set_type_hint(bs_table[cdrom_index], BDRV_TYPE_CDROM);
3635 /* open the virtual block devices */
3636 for(i = 0; i < MAX_DISKS; i++) {
3637 if (hd_filename[i]) {
3640 snprintf(buf, sizeof(buf), "hd%c", i + 'a');
3641 bs_table[i] = bdrv_new(buf);
3643 if (bdrv_open(bs_table[i], hd_filename[i], snapshot) < 0) {
3644 fprintf(stderr, "qemu: could not open hard disk image '%s'\n",
3648 if (i == 0 && cyls != 0) {
3649 bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
3650 bdrv_set_translation_hint(bs_table[i], translation);
3655 /* we always create at least one floppy disk */
3656 fd_table[0] = bdrv_new("fda");
3657 bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
3659 for(i = 0; i < MAX_FD; i++) {
3660 if (fd_filename[i]) {
3663 snprintf(buf, sizeof(buf), "fd%c", i + 'a');
3664 fd_table[i] = bdrv_new(buf);
3665 bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
3667 if (fd_filename[i] != '\0') {
3668 if (bdrv_open(fd_table[i], fd_filename[i], snapshot) < 0) {
3669 fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
3677 /* init CPU state */
3680 cpu_single_env = env;
3682 register_savevm("timer", 0, 1, timer_save, timer_load, env);
3683 register_savevm("cpu", 0, 3, cpu_save, cpu_load, env);
3684 register_savevm("ram", 0, 1, ram_save, ram_load, NULL);
3685 qemu_register_reset(main_cpu_reset, global_env);
3688 cpu_calibrate_ticks();
3692 dumb_display_init(ds);
3694 #if defined(CONFIG_SDL)
3695 sdl_display_init(ds, full_screen);
3696 #elif defined(CONFIG_COCOA)
3697 cocoa_display_init(ds, full_screen);
3699 dumb_display_init(ds);
3703 vga_console = graphic_console_init(ds);
3705 monitor_hd = qemu_chr_open(monitor_device);
3707 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
3710 monitor_init(monitor_hd, !nographic);
3712 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
3713 if (serial_devices[i][0] != '\0') {
3714 serial_hds[i] = qemu_chr_open(serial_devices[i]);
3715 if (!serial_hds[i]) {
3716 fprintf(stderr, "qemu: could not open serial device '%s'\n",
3720 if (!strcmp(serial_devices[i], "vc"))
3721 qemu_chr_printf(serial_hds[i], "serial%d console\n", i);
3725 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
3726 if (parallel_devices[i][0] != '\0') {
3727 parallel_hds[i] = qemu_chr_open(parallel_devices[i]);
3728 if (!parallel_hds[i]) {
3729 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
3730 parallel_devices[i]);
3733 if (!strcmp(parallel_devices[i], "vc"))
3734 qemu_chr_printf(parallel_hds[i], "parallel%d console\n", i);
3738 /* setup cpu signal handlers for MMU / self modifying code handling */
3739 #if !defined(CONFIG_SOFTMMU)
3741 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
3744 signal_stack = memalign(16, SIGNAL_STACK_SIZE);
3745 stk.ss_sp = signal_stack;
3746 stk.ss_size = SIGNAL_STACK_SIZE;
3749 if (sigaltstack(&stk, NULL) < 0) {
3750 perror("sigaltstack");
3756 struct sigaction act;
3758 sigfillset(&act.sa_mask);
3759 act.sa_flags = SA_SIGINFO;
3760 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
3761 act.sa_flags |= SA_ONSTACK;
3763 act.sa_sigaction = host_segv_handler;
3764 sigaction(SIGSEGV, &act, NULL);
3765 sigaction(SIGBUS, &act, NULL);
3766 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
3767 sigaction(SIGFPE, &act, NULL);
3774 struct sigaction act;
3775 sigfillset(&act.sa_mask);
3777 act.sa_handler = SIG_IGN;
3778 sigaction(SIGPIPE, &act, NULL);
3783 machine->init(ram_size, vga_ram_size, boot_device,
3784 ds, fd_filename, snapshot,
3785 kernel_filename, kernel_cmdline, initrd_filename);
3787 gui_timer = qemu_new_timer(rt_clock, gui_update, NULL);
3788 qemu_mod_timer(gui_timer, qemu_get_clock(rt_clock));
3790 #ifdef CONFIG_GDBSTUB
3792 if (gdbserver_start(gdbstub_port) < 0) {
3793 fprintf(stderr, "Could not open gdbserver socket on port %d\n",
3797 printf("Waiting gdb connection on port %d\n", gdbstub_port);
3802 qemu_loadvm(loadvm);
3805 /* XXX: simplify init */
3807 if (start_emulation) {