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;
131 int audio_enabled = 0;
132 int sb16_enabled = 0;
133 int adlib_enabled = 0;
135 int es1370_enabled = 0;
138 int prep_enabled = 0;
140 int cirrus_vga_enabled = 1;
142 int graphic_width = 1024;
143 int graphic_height = 768;
145 int graphic_width = 800;
146 int graphic_height = 600;
148 int graphic_depth = 15;
150 TextConsole *vga_console;
151 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
152 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
154 int win2k_install_hack = 0;
157 /***********************************************************/
158 /* x86 ISA bus support */
160 target_phys_addr_t isa_mem_base = 0;
163 uint32_t default_ioport_readb(void *opaque, uint32_t address)
165 #ifdef DEBUG_UNUSED_IOPORT
166 fprintf(stderr, "inb: port=0x%04x\n", address);
171 void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
173 #ifdef DEBUG_UNUSED_IOPORT
174 fprintf(stderr, "outb: port=0x%04x data=0x%02x\n", address, data);
178 /* default is to make two byte accesses */
179 uint32_t default_ioport_readw(void *opaque, uint32_t address)
182 data = ioport_read_table[0][address](ioport_opaque[address], address);
183 address = (address + 1) & (MAX_IOPORTS - 1);
184 data |= ioport_read_table[0][address](ioport_opaque[address], address) << 8;
188 void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
190 ioport_write_table[0][address](ioport_opaque[address], address, data & 0xff);
191 address = (address + 1) & (MAX_IOPORTS - 1);
192 ioport_write_table[0][address](ioport_opaque[address], address, (data >> 8) & 0xff);
195 uint32_t default_ioport_readl(void *opaque, uint32_t address)
197 #ifdef DEBUG_UNUSED_IOPORT
198 fprintf(stderr, "inl: port=0x%04x\n", address);
203 void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
205 #ifdef DEBUG_UNUSED_IOPORT
206 fprintf(stderr, "outl: port=0x%04x data=0x%02x\n", address, data);
210 void init_ioports(void)
214 for(i = 0; i < MAX_IOPORTS; i++) {
215 ioport_read_table[0][i] = default_ioport_readb;
216 ioport_write_table[0][i] = default_ioport_writeb;
217 ioport_read_table[1][i] = default_ioport_readw;
218 ioport_write_table[1][i] = default_ioport_writew;
219 ioport_read_table[2][i] = default_ioport_readl;
220 ioport_write_table[2][i] = default_ioport_writel;
224 /* size is the word size in byte */
225 int register_ioport_read(int start, int length, int size,
226 IOPortReadFunc *func, void *opaque)
232 } else if (size == 2) {
234 } else if (size == 4) {
237 hw_error("register_ioport_read: invalid size");
240 for(i = start; i < start + length; i += size) {
241 ioport_read_table[bsize][i] = func;
242 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
243 hw_error("register_ioport_read: invalid opaque");
244 ioport_opaque[i] = opaque;
249 /* size is the word size in byte */
250 int register_ioport_write(int start, int length, int size,
251 IOPortWriteFunc *func, void *opaque)
257 } else if (size == 2) {
259 } else if (size == 4) {
262 hw_error("register_ioport_write: invalid size");
265 for(i = start; i < start + length; i += size) {
266 ioport_write_table[bsize][i] = func;
267 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
268 hw_error("register_ioport_read: invalid opaque");
269 ioport_opaque[i] = opaque;
274 void isa_unassign_ioport(int start, int length)
278 for(i = start; i < start + length; i++) {
279 ioport_read_table[0][i] = default_ioport_readb;
280 ioport_read_table[1][i] = default_ioport_readw;
281 ioport_read_table[2][i] = default_ioport_readl;
283 ioport_write_table[0][i] = default_ioport_writeb;
284 ioport_write_table[1][i] = default_ioport_writew;
285 ioport_write_table[2][i] = default_ioport_writel;
289 /***********************************************************/
291 void pstrcpy(char *buf, int buf_size, const char *str)
301 if (c == 0 || q >= buf + buf_size - 1)
308 /* strcat and truncate. */
309 char *pstrcat(char *buf, int buf_size, const char *s)
314 pstrcpy(buf + len, buf_size - len, s);
318 int strstart(const char *str, const char *val, const char **ptr)
334 /* return the size or -1 if error */
335 int get_image_size(const char *filename)
338 fd = open(filename, O_RDONLY | O_BINARY);
341 size = lseek(fd, 0, SEEK_END);
346 /* return the size or -1 if error */
347 int load_image(const char *filename, uint8_t *addr)
350 fd = open(filename, O_RDONLY | O_BINARY);
353 size = lseek(fd, 0, SEEK_END);
354 lseek(fd, 0, SEEK_SET);
355 if (read(fd, addr, size) != size) {
363 void cpu_outb(CPUState *env, int addr, int val)
366 if (loglevel & CPU_LOG_IOPORT)
367 fprintf(logfile, "outb: %04x %02x\n", addr, val);
369 ioport_write_table[0][addr](ioport_opaque[addr], addr, val);
372 void cpu_outw(CPUState *env, int addr, int val)
375 if (loglevel & CPU_LOG_IOPORT)
376 fprintf(logfile, "outw: %04x %04x\n", addr, val);
378 ioport_write_table[1][addr](ioport_opaque[addr], addr, val);
381 void cpu_outl(CPUState *env, int addr, int val)
384 if (loglevel & CPU_LOG_IOPORT)
385 fprintf(logfile, "outl: %04x %08x\n", addr, val);
387 ioport_write_table[2][addr](ioport_opaque[addr], addr, val);
390 int cpu_inb(CPUState *env, int addr)
393 val = ioport_read_table[0][addr](ioport_opaque[addr], addr);
395 if (loglevel & CPU_LOG_IOPORT)
396 fprintf(logfile, "inb : %04x %02x\n", addr, val);
401 int cpu_inw(CPUState *env, int addr)
404 val = ioport_read_table[1][addr](ioport_opaque[addr], addr);
406 if (loglevel & CPU_LOG_IOPORT)
407 fprintf(logfile, "inw : %04x %04x\n", addr, val);
412 int cpu_inl(CPUState *env, int addr)
415 val = ioport_read_table[2][addr](ioport_opaque[addr], addr);
417 if (loglevel & CPU_LOG_IOPORT)
418 fprintf(logfile, "inl : %04x %08x\n", addr, val);
423 /***********************************************************/
424 void hw_error(const char *fmt, ...)
429 fprintf(stderr, "qemu: hardware error: ");
430 vfprintf(stderr, fmt, ap);
431 fprintf(stderr, "\n");
433 cpu_dump_state(global_env, stderr, fprintf, X86_DUMP_FPU | X86_DUMP_CCOP);
435 cpu_dump_state(global_env, stderr, fprintf, 0);
441 /***********************************************************/
444 static QEMUPutKBDEvent *qemu_put_kbd_event;
445 static void *qemu_put_kbd_event_opaque;
446 static QEMUPutMouseEvent *qemu_put_mouse_event;
447 static void *qemu_put_mouse_event_opaque;
449 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
451 qemu_put_kbd_event_opaque = opaque;
452 qemu_put_kbd_event = func;
455 void qemu_add_mouse_event_handler(QEMUPutMouseEvent *func, void *opaque)
457 qemu_put_mouse_event_opaque = opaque;
458 qemu_put_mouse_event = func;
461 void kbd_put_keycode(int keycode)
463 if (qemu_put_kbd_event) {
464 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
468 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
470 if (qemu_put_mouse_event) {
471 qemu_put_mouse_event(qemu_put_mouse_event_opaque,
472 dx, dy, dz, buttons_state);
476 /***********************************************************/
479 #if defined(__powerpc__)
481 static inline uint32_t get_tbl(void)
484 asm volatile("mftb %0" : "=r" (tbl));
488 static inline uint32_t get_tbu(void)
491 asm volatile("mftbu %0" : "=r" (tbl));
495 int64_t cpu_get_real_ticks(void)
498 /* NOTE: we test if wrapping has occurred */
504 return ((int64_t)h << 32) | l;
507 #elif defined(__i386__)
509 int64_t cpu_get_real_ticks(void)
512 asm volatile ("rdtsc" : "=A" (val));
516 #elif defined(__x86_64__)
518 int64_t cpu_get_real_ticks(void)
522 asm volatile("rdtsc" : "=a" (low), "=d" (high));
529 #elif defined(__ia64)
531 int64_t cpu_get_real_ticks(void)
534 asm volatile ("mov %0 = ar.itc" : "=r"(val) :: "memory");
538 #elif defined(__s390__)
540 int64_t cpu_get_real_ticks(void)
543 asm volatile("stck 0(%1)" : "=m" (val) : "a" (&val) : "cc");
548 #error unsupported CPU
551 static int64_t cpu_ticks_offset;
552 static int cpu_ticks_enabled;
554 static inline int64_t cpu_get_ticks(void)
556 if (!cpu_ticks_enabled) {
557 return cpu_ticks_offset;
559 return cpu_get_real_ticks() + cpu_ticks_offset;
563 /* enable cpu_get_ticks() */
564 void cpu_enable_ticks(void)
566 if (!cpu_ticks_enabled) {
567 cpu_ticks_offset -= cpu_get_real_ticks();
568 cpu_ticks_enabled = 1;
572 /* disable cpu_get_ticks() : the clock is stopped. You must not call
573 cpu_get_ticks() after that. */
574 void cpu_disable_ticks(void)
576 if (cpu_ticks_enabled) {
577 cpu_ticks_offset = cpu_get_ticks();
578 cpu_ticks_enabled = 0;
582 static int64_t get_clock(void)
587 return ((int64_t)tb.time * 1000 + (int64_t)tb.millitm) * 1000;
590 gettimeofday(&tv, NULL);
591 return tv.tv_sec * 1000000LL + tv.tv_usec;
595 void cpu_calibrate_ticks(void)
600 ticks = cpu_get_real_ticks();
606 usec = get_clock() - usec;
607 ticks = cpu_get_real_ticks() - ticks;
608 ticks_per_sec = (ticks * 1000000LL + (usec >> 1)) / usec;
611 /* compute with 96 bit intermediate result: (a*b)/c */
612 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
617 #ifdef WORDS_BIGENDIAN
627 rl = (uint64_t)u.l.low * (uint64_t)b;
628 rh = (uint64_t)u.l.high * (uint64_t)b;
631 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
635 #define QEMU_TIMER_REALTIME 0
636 #define QEMU_TIMER_VIRTUAL 1
640 /* XXX: add frequency */
648 struct QEMUTimer *next;
654 static QEMUTimer *active_timers[2];
656 static MMRESULT timerID;
658 /* frequency of the times() clock tick */
659 static int timer_freq;
662 QEMUClock *qemu_new_clock(int type)
665 clock = qemu_mallocz(sizeof(QEMUClock));
672 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
676 ts = qemu_mallocz(sizeof(QEMUTimer));
683 void qemu_free_timer(QEMUTimer *ts)
688 /* stop a timer, but do not dealloc it */
689 void qemu_del_timer(QEMUTimer *ts)
693 /* NOTE: this code must be signal safe because
694 qemu_timer_expired() can be called from a signal. */
695 pt = &active_timers[ts->clock->type];
708 /* modify the current timer so that it will be fired when current_time
709 >= expire_time. The corresponding callback will be called. */
710 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
716 /* add the timer in the sorted list */
717 /* NOTE: this code must be signal safe because
718 qemu_timer_expired() can be called from a signal. */
719 pt = &active_timers[ts->clock->type];
724 if (t->expire_time > expire_time)
728 ts->expire_time = expire_time;
733 int qemu_timer_pending(QEMUTimer *ts)
736 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
743 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
747 return (timer_head->expire_time <= current_time);
750 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
756 if (!ts || ts->expire_time > current_time)
758 /* remove timer from the list before calling the callback */
759 *ptimer_head = ts->next;
762 /* run the callback (the timer list can be modified) */
767 int64_t qemu_get_clock(QEMUClock *clock)
769 switch(clock->type) {
770 case QEMU_TIMER_REALTIME:
772 return GetTickCount();
777 /* Note that using gettimeofday() is not a good solution
778 for timers because its value change when the date is
780 if (timer_freq == 100) {
781 return times(&tp) * 10;
783 return ((int64_t)times(&tp) * 1000) / timer_freq;
788 case QEMU_TIMER_VIRTUAL:
789 return cpu_get_ticks();
794 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
796 uint64_t expire_time;
798 if (qemu_timer_pending(ts)) {
799 expire_time = ts->expire_time;
803 qemu_put_be64(f, expire_time);
806 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
808 uint64_t expire_time;
810 expire_time = qemu_get_be64(f);
811 if (expire_time != -1) {
812 qemu_mod_timer(ts, expire_time);
818 static void timer_save(QEMUFile *f, void *opaque)
820 if (cpu_ticks_enabled) {
821 hw_error("cannot save state if virtual timers are running");
823 qemu_put_be64s(f, &cpu_ticks_offset);
824 qemu_put_be64s(f, &ticks_per_sec);
827 static int timer_load(QEMUFile *f, void *opaque, int version_id)
831 if (cpu_ticks_enabled) {
834 qemu_get_be64s(f, &cpu_ticks_offset);
835 qemu_get_be64s(f, &ticks_per_sec);
840 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
841 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
843 static void host_alarm_handler(int host_signum)
847 #define DISP_FREQ 1000
849 static int64_t delta_min = INT64_MAX;
850 static int64_t delta_max, delta_cum, last_clock, delta, ti;
852 ti = qemu_get_clock(vm_clock);
853 if (last_clock != 0) {
854 delta = ti - last_clock;
855 if (delta < delta_min)
857 if (delta > delta_max)
860 if (++count == DISP_FREQ) {
861 printf("timer: min=%lld us max=%lld us avg=%lld us avg_freq=%0.3f Hz\n",
862 muldiv64(delta_min, 1000000, ticks_per_sec),
863 muldiv64(delta_max, 1000000, ticks_per_sec),
864 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
865 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
867 delta_min = INT64_MAX;
875 if (qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
876 qemu_get_clock(vm_clock)) ||
877 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
878 qemu_get_clock(rt_clock))) {
879 /* stop the cpu because a timer occured */
880 cpu_interrupt(global_env, CPU_INTERRUPT_EXIT);
882 if (global_env->kqemu_enabled) {
883 kqemu_cpu_interrupt(global_env);
891 #if defined(__linux__)
893 #define RTC_FREQ 1024
897 static int start_rtc_timer(void)
899 rtc_fd = open("/dev/rtc", O_RDONLY);
902 if (ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
903 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
904 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
905 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
908 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
913 pit_min_timer_count = PIT_FREQ / RTC_FREQ;
919 static int start_rtc_timer(void)
924 #endif /* !defined(__linux__) */
926 #endif /* !defined(_WIN32) */
928 static void init_timers(void)
930 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
931 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
936 timerID = timeSetEvent(1, // interval (ms)
938 host_alarm_handler, // function
939 (DWORD)&count, // user parameter
940 TIME_PERIODIC | TIME_CALLBACK_FUNCTION);
942 perror("failed timer alarm");
946 pit_min_timer_count = ((uint64_t)10000 * PIT_FREQ) / 1000000;
949 struct sigaction act;
950 struct itimerval itv;
952 /* get times() syscall frequency */
953 timer_freq = sysconf(_SC_CLK_TCK);
956 sigfillset(&act.sa_mask);
958 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
959 act.sa_flags |= SA_ONSTACK;
961 act.sa_handler = host_alarm_handler;
962 sigaction(SIGALRM, &act, NULL);
964 itv.it_interval.tv_sec = 0;
965 itv.it_interval.tv_usec = 999; /* for i386 kernel 2.6 to get 1 ms */
966 itv.it_value.tv_sec = 0;
967 itv.it_value.tv_usec = 10 * 1000;
968 setitimer(ITIMER_REAL, &itv, NULL);
969 /* we probe the tick duration of the kernel to inform the user if
970 the emulated kernel requested a too high timer frequency */
971 getitimer(ITIMER_REAL, &itv);
973 #if defined(__linux__)
974 if (itv.it_interval.tv_usec > 1000) {
975 /* try to use /dev/rtc to have a faster timer */
976 if (start_rtc_timer() < 0)
979 itv.it_interval.tv_sec = 0;
980 itv.it_interval.tv_usec = 0;
981 itv.it_value.tv_sec = 0;
982 itv.it_value.tv_usec = 0;
983 setitimer(ITIMER_REAL, &itv, NULL);
986 sigaction(SIGIO, &act, NULL);
987 fcntl(rtc_fd, F_SETFL, O_ASYNC);
988 fcntl(rtc_fd, F_SETOWN, getpid());
990 #endif /* defined(__linux__) */
993 pit_min_timer_count = ((uint64_t)itv.it_interval.tv_usec *
1000 void quit_timers(void)
1003 timeKillEvent(timerID);
1007 /***********************************************************/
1008 /* character device */
1010 int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1012 return s->chr_write(s, buf, len);
1015 void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1020 vsnprintf(buf, sizeof(buf), fmt, ap);
1021 qemu_chr_write(s, buf, strlen(buf));
1025 void qemu_chr_send_event(CharDriverState *s, int event)
1027 if (s->chr_send_event)
1028 s->chr_send_event(s, event);
1031 void qemu_chr_add_read_handler(CharDriverState *s,
1032 IOCanRWHandler *fd_can_read,
1033 IOReadHandler *fd_read, void *opaque)
1035 s->chr_add_read_handler(s, fd_can_read, fd_read, opaque);
1038 void qemu_chr_add_event_handler(CharDriverState *s, IOEventHandler *chr_event)
1040 s->chr_event = chr_event;
1043 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1048 static void null_chr_add_read_handler(CharDriverState *chr,
1049 IOCanRWHandler *fd_can_read,
1050 IOReadHandler *fd_read, void *opaque)
1054 CharDriverState *qemu_chr_open_null(void)
1056 CharDriverState *chr;
1058 chr = qemu_mallocz(sizeof(CharDriverState));
1061 chr->chr_write = null_chr_write;
1062 chr->chr_add_read_handler = null_chr_add_read_handler;
1070 /* for nographic stdio only */
1071 IOCanRWHandler *fd_can_read;
1072 IOReadHandler *fd_read;
1076 #define STDIO_MAX_CLIENTS 2
1078 static int stdio_nb_clients;
1079 static CharDriverState *stdio_clients[STDIO_MAX_CLIENTS];
1081 static int unix_write(int fd, const uint8_t *buf, int len1)
1087 ret = write(fd, buf, len);
1089 if (errno != EINTR && errno != EAGAIN)
1091 } else if (ret == 0) {
1101 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1103 FDCharDriver *s = chr->opaque;
1104 return unix_write(s->fd_out, buf, len);
1107 static void fd_chr_add_read_handler(CharDriverState *chr,
1108 IOCanRWHandler *fd_can_read,
1109 IOReadHandler *fd_read, void *opaque)
1111 FDCharDriver *s = chr->opaque;
1113 if (nographic && s->fd_in == 0) {
1114 s->fd_can_read = fd_can_read;
1115 s->fd_read = fd_read;
1116 s->fd_opaque = opaque;
1118 qemu_add_fd_read_handler(s->fd_in, fd_can_read, fd_read, opaque);
1122 /* open a character device to a unix fd */
1123 CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
1125 CharDriverState *chr;
1128 chr = qemu_mallocz(sizeof(CharDriverState));
1131 s = qemu_mallocz(sizeof(FDCharDriver));
1139 chr->chr_write = fd_chr_write;
1140 chr->chr_add_read_handler = fd_chr_add_read_handler;
1144 /* for STDIO, we handle the case where several clients use it
1147 #define TERM_ESCAPE 0x01 /* ctrl-a is used for escape */
1149 #define TERM_FIFO_MAX_SIZE 1
1151 static int term_got_escape, client_index;
1152 static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
1155 void term_print_help(void)
1158 "C-a h print this help\n"
1159 "C-a x exit emulator\n"
1160 "C-a s save disk data back to file (if -snapshot)\n"
1161 "C-a b send break (magic sysrq)\n"
1162 "C-a c switch between console and monitor\n"
1163 "C-a C-a send C-a\n"
1167 /* called when a char is received */
1168 static void stdio_received_byte(int ch)
1170 if (term_got_escape) {
1171 term_got_escape = 0;
1182 for (i = 0; i < MAX_DISKS; i++) {
1184 bdrv_commit(bs_table[i]);
1189 if (client_index < stdio_nb_clients) {
1190 CharDriverState *chr;
1193 chr = stdio_clients[client_index];
1195 chr->chr_event(s->fd_opaque, CHR_EVENT_BREAK);
1200 if (client_index >= stdio_nb_clients)
1202 if (client_index == 0) {
1203 /* send a new line in the monitor to get the prompt */
1211 } else if (ch == TERM_ESCAPE) {
1212 term_got_escape = 1;
1215 if (client_index < stdio_nb_clients) {
1217 CharDriverState *chr;
1220 chr = stdio_clients[client_index];
1222 if (s->fd_can_read(s->fd_opaque) > 0) {
1224 s->fd_read(s->fd_opaque, buf, 1);
1225 } else if (term_fifo_size == 0) {
1226 term_fifo[term_fifo_size++] = ch;
1232 static int stdio_can_read(void *opaque)
1234 CharDriverState *chr;
1237 if (client_index < stdio_nb_clients) {
1238 chr = stdio_clients[client_index];
1240 /* try to flush the queue if needed */
1241 if (term_fifo_size != 0 && s->fd_can_read(s->fd_opaque) > 0) {
1242 s->fd_read(s->fd_opaque, term_fifo, 1);
1245 /* see if we can absorb more chars */
1246 if (term_fifo_size == 0)
1255 static void stdio_read(void *opaque, const uint8_t *buf, int size)
1258 for(i = 0; i < size; i++)
1259 stdio_received_byte(buf[i]);
1262 /* init terminal so that we can grab keys */
1263 static struct termios oldtty;
1264 static int old_fd0_flags;
1266 static void term_exit(void)
1268 tcsetattr (0, TCSANOW, &oldtty);
1269 fcntl(0, F_SETFL, old_fd0_flags);
1272 static void term_init(void)
1276 tcgetattr (0, &tty);
1278 old_fd0_flags = fcntl(0, F_GETFL);
1280 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1281 |INLCR|IGNCR|ICRNL|IXON);
1282 tty.c_oflag |= OPOST;
1283 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1284 /* if graphical mode, we allow Ctrl-C handling */
1286 tty.c_lflag &= ~ISIG;
1287 tty.c_cflag &= ~(CSIZE|PARENB);
1290 tty.c_cc[VTIME] = 0;
1292 tcsetattr (0, TCSANOW, &tty);
1296 fcntl(0, F_SETFL, O_NONBLOCK);
1299 CharDriverState *qemu_chr_open_stdio(void)
1301 CharDriverState *chr;
1304 if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
1306 chr = qemu_chr_open_fd(0, 1);
1307 if (stdio_nb_clients == 0)
1308 qemu_add_fd_read_handler(0, stdio_can_read, stdio_read, NULL);
1309 client_index = stdio_nb_clients;
1311 if (stdio_nb_clients != 0)
1313 chr = qemu_chr_open_fd(0, 1);
1315 stdio_clients[stdio_nb_clients++] = chr;
1316 if (stdio_nb_clients == 1) {
1317 /* set the terminal in raw mode */
1323 #if defined(__linux__)
1324 CharDriverState *qemu_chr_open_pty(void)
1326 char slave_name[1024];
1327 int master_fd, slave_fd;
1329 /* Not satisfying */
1330 if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
1333 fprintf(stderr, "char device redirected to %s\n", slave_name);
1334 return qemu_chr_open_fd(master_fd, master_fd);
1337 CharDriverState *qemu_chr_open_pty(void)
1343 #endif /* !defined(_WIN32) */
1345 CharDriverState *qemu_chr_open(const char *filename)
1347 if (!strcmp(filename, "vc")) {
1348 return text_console_init(&display_state);
1349 } else if (!strcmp(filename, "null")) {
1350 return qemu_chr_open_null();
1353 if (!strcmp(filename, "pty")) {
1354 return qemu_chr_open_pty();
1355 } else if (!strcmp(filename, "stdio")) {
1356 return qemu_chr_open_stdio();
1364 /***********************************************************/
1365 /* Linux network device redirectors */
1367 void hex_dump(FILE *f, const uint8_t *buf, int size)
1371 for(i=0;i<size;i+=16) {
1375 fprintf(f, "%08x ", i);
1378 fprintf(f, " %02x", buf[i+j]);
1383 for(j=0;j<len;j++) {
1385 if (c < ' ' || c > '~')
1387 fprintf(f, "%c", c);
1393 void qemu_send_packet(NetDriverState *nd, const uint8_t *buf, int size)
1395 nd->send_packet(nd, buf, size);
1398 void qemu_add_read_packet(NetDriverState *nd, IOCanRWHandler *fd_can_read,
1399 IOReadHandler *fd_read, void *opaque)
1401 nd->add_read_packet(nd, fd_can_read, fd_read, opaque);
1404 /* dummy network adapter */
1406 static void dummy_send_packet(NetDriverState *nd, const uint8_t *buf, int size)
1410 static void dummy_add_read_packet(NetDriverState *nd,
1411 IOCanRWHandler *fd_can_read,
1412 IOReadHandler *fd_read, void *opaque)
1416 static int net_dummy_init(NetDriverState *nd)
1418 nd->send_packet = dummy_send_packet;
1419 nd->add_read_packet = dummy_add_read_packet;
1420 pstrcpy(nd->ifname, sizeof(nd->ifname), "dummy");
1424 #if defined(CONFIG_SLIRP)
1426 /* slirp network adapter */
1428 static void *slirp_fd_opaque;
1429 static IOCanRWHandler *slirp_fd_can_read;
1430 static IOReadHandler *slirp_fd_read;
1431 static int slirp_inited;
1433 int slirp_can_output(void)
1435 return slirp_fd_can_read(slirp_fd_opaque);
1438 void slirp_output(const uint8_t *pkt, int pkt_len)
1441 printf("output:\n");
1442 hex_dump(stdout, pkt, pkt_len);
1444 slirp_fd_read(slirp_fd_opaque, pkt, pkt_len);
1447 static void slirp_send_packet(NetDriverState *nd, const uint8_t *buf, int size)
1451 hex_dump(stdout, buf, size);
1453 slirp_input(buf, size);
1456 static void slirp_add_read_packet(NetDriverState *nd,
1457 IOCanRWHandler *fd_can_read,
1458 IOReadHandler *fd_read, void *opaque)
1460 slirp_fd_opaque = opaque;
1461 slirp_fd_can_read = fd_can_read;
1462 slirp_fd_read = fd_read;
1465 static int net_slirp_init(NetDriverState *nd)
1467 if (!slirp_inited) {
1471 nd->send_packet = slirp_send_packet;
1472 nd->add_read_packet = slirp_add_read_packet;
1473 pstrcpy(nd->ifname, sizeof(nd->ifname), "slirp");
1477 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
1482 p1 = strchr(p, sep);
1488 if (len > buf_size - 1)
1490 memcpy(buf, p, len);
1497 static void net_slirp_redir(const char *redir_str)
1502 struct in_addr guest_addr;
1503 int host_port, guest_port;
1505 if (!slirp_inited) {
1511 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
1513 if (!strcmp(buf, "tcp")) {
1515 } else if (!strcmp(buf, "udp")) {
1521 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
1523 host_port = strtol(buf, &r, 0);
1527 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
1529 if (buf[0] == '\0') {
1530 pstrcpy(buf, sizeof(buf), "10.0.2.15");
1532 if (!inet_aton(buf, &guest_addr))
1535 guest_port = strtol(p, &r, 0);
1539 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
1540 fprintf(stderr, "qemu: could not set up redirection\n");
1545 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
1553 static void smb_exit(void)
1557 char filename[1024];
1559 /* erase all the files in the directory */
1560 d = opendir(smb_dir);
1565 if (strcmp(de->d_name, ".") != 0 &&
1566 strcmp(de->d_name, "..") != 0) {
1567 snprintf(filename, sizeof(filename), "%s/%s",
1568 smb_dir, de->d_name);
1576 /* automatic user mode samba server configuration */
1577 void net_slirp_smb(const char *exported_dir)
1579 char smb_conf[1024];
1580 char smb_cmdline[1024];
1583 if (!slirp_inited) {
1588 /* XXX: better tmp dir construction */
1589 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
1590 if (mkdir(smb_dir, 0700) < 0) {
1591 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
1594 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
1596 f = fopen(smb_conf, "w");
1598 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
1605 "socket address=127.0.0.1\n"
1606 "pid directory=%s\n"
1607 "lock directory=%s\n"
1608 "log file=%s/log.smbd\n"
1609 "smb passwd file=%s/smbpasswd\n"
1610 "security = share\n"
1625 snprintf(smb_cmdline, sizeof(smb_cmdline), "/usr/sbin/smbd -s %s",
1628 slirp_add_exec(0, smb_cmdline, 4, 139);
1631 #endif /* !defined(_WIN32) */
1633 #endif /* CONFIG_SLIRP */
1635 #if !defined(_WIN32)
1637 static int tun_open(char *ifname, int ifname_size)
1643 fd = open("/dev/tap", O_RDWR);
1645 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
1650 dev = devname(s.st_rdev, S_IFCHR);
1651 pstrcpy(ifname, ifname_size, dev);
1653 fcntl(fd, F_SETFL, O_NONBLOCK);
1657 static int tun_open(char *ifname, int ifname_size)
1662 fd = open("/dev/net/tun", O_RDWR);
1664 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
1667 memset(&ifr, 0, sizeof(ifr));
1668 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
1669 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tun%d");
1670 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
1672 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
1676 printf("Connected to host network interface: %s\n", ifr.ifr_name);
1677 pstrcpy(ifname, ifname_size, ifr.ifr_name);
1678 fcntl(fd, F_SETFL, O_NONBLOCK);
1683 static void tun_send_packet(NetDriverState *nd, const uint8_t *buf, int size)
1685 write(nd->fd, buf, size);
1688 static void tun_add_read_packet(NetDriverState *nd,
1689 IOCanRWHandler *fd_can_read,
1690 IOReadHandler *fd_read, void *opaque)
1692 qemu_add_fd_read_handler(nd->fd, fd_can_read, fd_read, opaque);
1695 static int net_tun_init(NetDriverState *nd)
1701 nd->fd = tun_open(nd->ifname, sizeof(nd->ifname));
1705 /* try to launch network init script */
1710 *parg++ = network_script;
1711 *parg++ = nd->ifname;
1713 execv(network_script, args);
1716 while (waitpid(pid, &status, 0) != pid);
1717 if (!WIFEXITED(status) ||
1718 WEXITSTATUS(status) != 0) {
1719 fprintf(stderr, "%s: could not launch network script\n",
1723 nd->send_packet = tun_send_packet;
1724 nd->add_read_packet = tun_add_read_packet;
1728 static int net_fd_init(NetDriverState *nd, int fd)
1731 nd->send_packet = tun_send_packet;
1732 nd->add_read_packet = tun_add_read_packet;
1733 pstrcpy(nd->ifname, sizeof(nd->ifname), "tunfd");
1737 #endif /* !_WIN32 */
1739 /***********************************************************/
1742 static char *pid_filename;
1744 /* Remove PID file. Called on normal exit */
1746 static void remove_pidfile(void)
1748 unlink (pid_filename);
1751 static void create_pidfile(const char *filename)
1753 struct stat pidstat;
1756 /* Try to write our PID to the named file */
1757 if (stat(filename, &pidstat) < 0) {
1758 if (errno == ENOENT) {
1759 if ((f = fopen (filename, "w")) == NULL) {
1760 perror("Opening pidfile");
1763 fprintf(f, "%d\n", getpid());
1765 pid_filename = qemu_strdup(filename);
1766 if (!pid_filename) {
1767 fprintf(stderr, "Could not save PID filename");
1770 atexit(remove_pidfile);
1773 fprintf(stderr, "%s already exists. Remove it and try again.\n",
1779 /***********************************************************/
1782 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
1786 static void dumb_resize(DisplayState *ds, int w, int h)
1790 static void dumb_refresh(DisplayState *ds)
1792 vga_update_display();
1795 void dumb_display_init(DisplayState *ds)
1800 ds->dpy_update = dumb_update;
1801 ds->dpy_resize = dumb_resize;
1802 ds->dpy_refresh = dumb_refresh;
1805 #if !defined(CONFIG_SOFTMMU)
1806 /***********************************************************/
1807 /* cpu signal handler */
1808 static void host_segv_handler(int host_signum, siginfo_t *info,
1811 if (cpu_signal_handler(host_signum, info, puc))
1813 if (stdio_nb_clients > 0)
1819 /***********************************************************/
1822 #define MAX_IO_HANDLERS 64
1824 typedef struct IOHandlerRecord {
1826 IOCanRWHandler *fd_can_read;
1827 IOReadHandler *fd_read;
1829 /* temporary data */
1832 struct IOHandlerRecord *next;
1835 static IOHandlerRecord *first_io_handler;
1837 int qemu_add_fd_read_handler(int fd, IOCanRWHandler *fd_can_read,
1838 IOReadHandler *fd_read, void *opaque)
1840 IOHandlerRecord *ioh;
1842 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
1846 ioh->fd_can_read = fd_can_read;
1847 ioh->fd_read = fd_read;
1848 ioh->opaque = opaque;
1849 ioh->next = first_io_handler;
1850 first_io_handler = ioh;
1854 void qemu_del_fd_read_handler(int fd)
1856 IOHandlerRecord **pioh, *ioh;
1858 pioh = &first_io_handler;
1863 if (ioh->fd == fd) {
1871 /***********************************************************/
1872 /* savevm/loadvm support */
1874 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
1876 fwrite(buf, 1, size, f);
1879 void qemu_put_byte(QEMUFile *f, int v)
1884 void qemu_put_be16(QEMUFile *f, unsigned int v)
1886 qemu_put_byte(f, v >> 8);
1887 qemu_put_byte(f, v);
1890 void qemu_put_be32(QEMUFile *f, unsigned int v)
1892 qemu_put_byte(f, v >> 24);
1893 qemu_put_byte(f, v >> 16);
1894 qemu_put_byte(f, v >> 8);
1895 qemu_put_byte(f, v);
1898 void qemu_put_be64(QEMUFile *f, uint64_t v)
1900 qemu_put_be32(f, v >> 32);
1901 qemu_put_be32(f, v);
1904 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size)
1906 return fread(buf, 1, size, f);
1909 int qemu_get_byte(QEMUFile *f)
1919 unsigned int qemu_get_be16(QEMUFile *f)
1922 v = qemu_get_byte(f) << 8;
1923 v |= qemu_get_byte(f);
1927 unsigned int qemu_get_be32(QEMUFile *f)
1930 v = qemu_get_byte(f) << 24;
1931 v |= qemu_get_byte(f) << 16;
1932 v |= qemu_get_byte(f) << 8;
1933 v |= qemu_get_byte(f);
1937 uint64_t qemu_get_be64(QEMUFile *f)
1940 v = (uint64_t)qemu_get_be32(f) << 32;
1941 v |= qemu_get_be32(f);
1945 int64_t qemu_ftell(QEMUFile *f)
1950 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
1952 if (fseek(f, pos, whence) < 0)
1957 typedef struct SaveStateEntry {
1961 SaveStateHandler *save_state;
1962 LoadStateHandler *load_state;
1964 struct SaveStateEntry *next;
1967 static SaveStateEntry *first_se;
1969 int register_savevm(const char *idstr,
1972 SaveStateHandler *save_state,
1973 LoadStateHandler *load_state,
1976 SaveStateEntry *se, **pse;
1978 se = qemu_malloc(sizeof(SaveStateEntry));
1981 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
1982 se->instance_id = instance_id;
1983 se->version_id = version_id;
1984 se->save_state = save_state;
1985 se->load_state = load_state;
1986 se->opaque = opaque;
1989 /* add at the end of list */
1991 while (*pse != NULL)
1992 pse = &(*pse)->next;
1997 #define QEMU_VM_FILE_MAGIC 0x5145564d
1998 #define QEMU_VM_FILE_VERSION 0x00000001
2000 int qemu_savevm(const char *filename)
2004 int len, len_pos, cur_pos, saved_vm_running, ret;
2006 saved_vm_running = vm_running;
2009 f = fopen(filename, "wb");
2015 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
2016 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
2018 for(se = first_se; se != NULL; se = se->next) {
2020 len = strlen(se->idstr);
2021 qemu_put_byte(f, len);
2022 qemu_put_buffer(f, se->idstr, len);
2024 qemu_put_be32(f, se->instance_id);
2025 qemu_put_be32(f, se->version_id);
2027 /* record size: filled later */
2029 qemu_put_be32(f, 0);
2031 se->save_state(f, se->opaque);
2033 /* fill record size */
2035 len = ftell(f) - len_pos - 4;
2036 fseek(f, len_pos, SEEK_SET);
2037 qemu_put_be32(f, len);
2038 fseek(f, cur_pos, SEEK_SET);
2044 if (saved_vm_running)
2049 static SaveStateEntry *find_se(const char *idstr, int instance_id)
2053 for(se = first_se; se != NULL; se = se->next) {
2054 if (!strcmp(se->idstr, idstr) &&
2055 instance_id == se->instance_id)
2061 int qemu_loadvm(const char *filename)
2065 int len, cur_pos, ret, instance_id, record_len, version_id;
2066 int saved_vm_running;
2070 saved_vm_running = vm_running;
2073 f = fopen(filename, "rb");
2079 v = qemu_get_be32(f);
2080 if (v != QEMU_VM_FILE_MAGIC)
2082 v = qemu_get_be32(f);
2083 if (v != QEMU_VM_FILE_VERSION) {
2090 #if defined (DO_TB_FLUSH)
2091 tb_flush(global_env);
2093 len = qemu_get_byte(f);
2096 qemu_get_buffer(f, idstr, len);
2098 instance_id = qemu_get_be32(f);
2099 version_id = qemu_get_be32(f);
2100 record_len = qemu_get_be32(f);
2102 printf("idstr=%s instance=0x%x version=%d len=%d\n",
2103 idstr, instance_id, version_id, record_len);
2106 se = find_se(idstr, instance_id);
2108 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
2109 instance_id, idstr);
2111 ret = se->load_state(f, se->opaque, version_id);
2113 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
2114 instance_id, idstr);
2117 /* always seek to exact end of record */
2118 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
2123 if (saved_vm_running)
2128 /***********************************************************/
2129 /* cpu save/restore */
2131 #if defined(TARGET_I386)
2133 static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
2135 qemu_put_be32(f, dt->selector);
2136 qemu_put_betl(f, dt->base);
2137 qemu_put_be32(f, dt->limit);
2138 qemu_put_be32(f, dt->flags);
2141 static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
2143 dt->selector = qemu_get_be32(f);
2144 dt->base = qemu_get_betl(f);
2145 dt->limit = qemu_get_be32(f);
2146 dt->flags = qemu_get_be32(f);
2149 void cpu_save(QEMUFile *f, void *opaque)
2151 CPUState *env = opaque;
2152 uint16_t fptag, fpus, fpuc, fpregs_format;
2156 for(i = 0; i < CPU_NB_REGS; i++)
2157 qemu_put_betls(f, &env->regs[i]);
2158 qemu_put_betls(f, &env->eip);
2159 qemu_put_betls(f, &env->eflags);
2160 hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
2161 qemu_put_be32s(f, &hflags);
2165 fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
2167 for(i = 0; i < 8; i++) {
2168 fptag |= ((!env->fptags[i]) << i);
2171 qemu_put_be16s(f, &fpuc);
2172 qemu_put_be16s(f, &fpus);
2173 qemu_put_be16s(f, &fptag);
2175 #ifdef USE_X86LDOUBLE
2180 qemu_put_be16s(f, &fpregs_format);
2182 for(i = 0; i < 8; i++) {
2183 #ifdef USE_X86LDOUBLE
2187 /* we save the real CPU data (in case of MMX usage only 'mant'
2188 contains the MMX register */
2189 cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
2190 qemu_put_be64(f, mant);
2191 qemu_put_be16(f, exp);
2194 /* if we use doubles for float emulation, we save the doubles to
2195 avoid losing information in case of MMX usage. It can give
2196 problems if the image is restored on a CPU where long
2197 doubles are used instead. */
2198 qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
2202 for(i = 0; i < 6; i++)
2203 cpu_put_seg(f, &env->segs[i]);
2204 cpu_put_seg(f, &env->ldt);
2205 cpu_put_seg(f, &env->tr);
2206 cpu_put_seg(f, &env->gdt);
2207 cpu_put_seg(f, &env->idt);
2209 qemu_put_be32s(f, &env->sysenter_cs);
2210 qemu_put_be32s(f, &env->sysenter_esp);
2211 qemu_put_be32s(f, &env->sysenter_eip);
2213 qemu_put_betls(f, &env->cr[0]);
2214 qemu_put_betls(f, &env->cr[2]);
2215 qemu_put_betls(f, &env->cr[3]);
2216 qemu_put_betls(f, &env->cr[4]);
2218 for(i = 0; i < 8; i++)
2219 qemu_put_betls(f, &env->dr[i]);
2222 qemu_put_be32s(f, &env->a20_mask);
2225 qemu_put_be32s(f, &env->mxcsr);
2226 for(i = 0; i < CPU_NB_REGS; i++) {
2227 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
2228 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
2231 #ifdef TARGET_X86_64
2232 qemu_put_be64s(f, &env->efer);
2233 qemu_put_be64s(f, &env->star);
2234 qemu_put_be64s(f, &env->lstar);
2235 qemu_put_be64s(f, &env->cstar);
2236 qemu_put_be64s(f, &env->fmask);
2237 qemu_put_be64s(f, &env->kernelgsbase);
2241 #ifdef USE_X86LDOUBLE
2242 /* XXX: add that in a FPU generic layer */
2243 union x86_longdouble {
2248 #define MANTD1(fp) (fp & ((1LL << 52) - 1))
2249 #define EXPBIAS1 1023
2250 #define EXPD1(fp) ((fp >> 52) & 0x7FF)
2251 #define SIGND1(fp) ((fp >> 32) & 0x80000000)
2253 static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
2257 p->mant = (MANTD1(temp) << 11) | (1LL << 63);
2258 /* exponent + sign */
2259 e = EXPD1(temp) - EXPBIAS1 + 16383;
2260 e |= SIGND1(temp) >> 16;
2265 int cpu_load(QEMUFile *f, void *opaque, int version_id)
2267 CPUState *env = opaque;
2270 uint16_t fpus, fpuc, fptag, fpregs_format;
2272 if (version_id != 3)
2274 for(i = 0; i < CPU_NB_REGS; i++)
2275 qemu_get_betls(f, &env->regs[i]);
2276 qemu_get_betls(f, &env->eip);
2277 qemu_get_betls(f, &env->eflags);
2278 qemu_get_be32s(f, &hflags);
2280 qemu_get_be16s(f, &fpuc);
2281 qemu_get_be16s(f, &fpus);
2282 qemu_get_be16s(f, &fptag);
2283 qemu_get_be16s(f, &fpregs_format);
2285 /* NOTE: we cannot always restore the FPU state if the image come
2286 from a host with a different 'USE_X86LDOUBLE' define. We guess
2287 if we are in an MMX state to restore correctly in that case. */
2288 guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
2289 for(i = 0; i < 8; i++) {
2293 switch(fpregs_format) {
2295 mant = qemu_get_be64(f);
2296 exp = qemu_get_be16(f);
2297 #ifdef USE_X86LDOUBLE
2298 env->fpregs[i].d = cpu_set_fp80(mant, exp);
2300 /* difficult case */
2302 env->fpregs[i].mmx.MMX_Q(0) = mant;
2304 env->fpregs[i].d = cpu_set_fp80(mant, exp);
2308 mant = qemu_get_be64(f);
2309 #ifdef USE_X86LDOUBLE
2311 union x86_longdouble *p;
2312 /* difficult case */
2313 p = (void *)&env->fpregs[i];
2318 fp64_to_fp80(p, mant);
2322 env->fpregs[i].mmx.MMX_Q(0) = mant;
2331 /* XXX: restore FPU round state */
2332 env->fpstt = (fpus >> 11) & 7;
2333 env->fpus = fpus & ~0x3800;
2335 for(i = 0; i < 8; i++) {
2336 env->fptags[i] = (fptag >> i) & 1;
2339 for(i = 0; i < 6; i++)
2340 cpu_get_seg(f, &env->segs[i]);
2341 cpu_get_seg(f, &env->ldt);
2342 cpu_get_seg(f, &env->tr);
2343 cpu_get_seg(f, &env->gdt);
2344 cpu_get_seg(f, &env->idt);
2346 qemu_get_be32s(f, &env->sysenter_cs);
2347 qemu_get_be32s(f, &env->sysenter_esp);
2348 qemu_get_be32s(f, &env->sysenter_eip);
2350 qemu_get_betls(f, &env->cr[0]);
2351 qemu_get_betls(f, &env->cr[2]);
2352 qemu_get_betls(f, &env->cr[3]);
2353 qemu_get_betls(f, &env->cr[4]);
2355 for(i = 0; i < 8; i++)
2356 qemu_get_betls(f, &env->dr[i]);
2359 qemu_get_be32s(f, &env->a20_mask);
2361 qemu_get_be32s(f, &env->mxcsr);
2362 for(i = 0; i < CPU_NB_REGS; i++) {
2363 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
2364 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
2367 #ifdef TARGET_X86_64
2368 qemu_get_be64s(f, &env->efer);
2369 qemu_get_be64s(f, &env->star);
2370 qemu_get_be64s(f, &env->lstar);
2371 qemu_get_be64s(f, &env->cstar);
2372 qemu_get_be64s(f, &env->fmask);
2373 qemu_get_be64s(f, &env->kernelgsbase);
2376 /* XXX: compute hflags from scratch, except for CPL and IIF */
2377 env->hflags = hflags;
2382 #elif defined(TARGET_PPC)
2383 void cpu_save(QEMUFile *f, void *opaque)
2387 int cpu_load(QEMUFile *f, void *opaque, int version_id)
2392 #elif defined(TARGET_MIPS)
2393 void cpu_save(QEMUFile *f, void *opaque)
2397 int cpu_load(QEMUFile *f, void *opaque, int version_id)
2402 #elif defined(TARGET_SPARC)
2403 void cpu_save(QEMUFile *f, void *opaque)
2405 CPUState *env = opaque;
2409 for(i = 0; i < 8; i++)
2410 qemu_put_betls(f, &env->gregs[i]);
2411 for(i = 0; i < NWINDOWS * 16; i++)
2412 qemu_put_betls(f, &env->regbase[i]);
2415 for(i = 0; i < TARGET_FPREGS; i++) {
2421 qemu_put_betl(f, u.i);
2424 qemu_put_betls(f, &env->pc);
2425 qemu_put_betls(f, &env->npc);
2426 qemu_put_betls(f, &env->y);
2428 qemu_put_be32(f, tmp);
2429 qemu_put_betls(f, &env->fsr);
2430 qemu_put_betls(f, &env->tbr);
2431 #ifndef TARGET_SPARC64
2432 qemu_put_be32s(f, &env->wim);
2434 for(i = 0; i < 16; i++)
2435 qemu_put_be32s(f, &env->mmuregs[i]);
2439 int cpu_load(QEMUFile *f, void *opaque, int version_id)
2441 CPUState *env = opaque;
2445 for(i = 0; i < 8; i++)
2446 qemu_get_betls(f, &env->gregs[i]);
2447 for(i = 0; i < NWINDOWS * 16; i++)
2448 qemu_get_betls(f, &env->regbase[i]);
2451 for(i = 0; i < TARGET_FPREGS; i++) {
2456 u.i = qemu_get_betl(f);
2460 qemu_get_betls(f, &env->pc);
2461 qemu_get_betls(f, &env->npc);
2462 qemu_get_betls(f, &env->y);
2463 tmp = qemu_get_be32(f);
2464 env->cwp = 0; /* needed to ensure that the wrapping registers are
2465 correctly updated */
2467 qemu_get_betls(f, &env->fsr);
2468 qemu_get_betls(f, &env->tbr);
2469 #ifndef TARGET_SPARC64
2470 qemu_get_be32s(f, &env->wim);
2472 for(i = 0; i < 16; i++)
2473 qemu_get_be32s(f, &env->mmuregs[i]);
2480 #warning No CPU save/restore functions
2484 /***********************************************************/
2485 /* ram save/restore */
2487 /* we just avoid storing empty pages */
2488 static void ram_put_page(QEMUFile *f, const uint8_t *buf, int len)
2493 for(i = 1; i < len; i++) {
2497 qemu_put_byte(f, 1);
2498 qemu_put_byte(f, v);
2501 qemu_put_byte(f, 0);
2502 qemu_put_buffer(f, buf, len);
2505 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
2509 v = qemu_get_byte(f);
2512 if (qemu_get_buffer(f, buf, len) != len)
2516 v = qemu_get_byte(f);
2517 memset(buf, v, len);
2525 static void ram_save(QEMUFile *f, void *opaque)
2528 qemu_put_be32(f, phys_ram_size);
2529 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
2530 ram_put_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
2534 static int ram_load(QEMUFile *f, void *opaque, int version_id)
2538 if (version_id != 1)
2540 if (qemu_get_be32(f) != phys_ram_size)
2542 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
2543 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
2550 /***********************************************************/
2551 /* machine registration */
2553 QEMUMachine *first_machine = NULL;
2555 int qemu_register_machine(QEMUMachine *m)
2558 pm = &first_machine;
2566 QEMUMachine *find_machine(const char *name)
2570 for(m = first_machine; m != NULL; m = m->next) {
2571 if (!strcmp(m->name, name))
2577 /***********************************************************/
2578 /* main execution loop */
2580 void gui_update(void *opaque)
2582 display_state.dpy_refresh(&display_state);
2583 qemu_mod_timer(gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
2586 /* XXX: support several handlers */
2587 VMStopHandler *vm_stop_cb;
2588 VMStopHandler *vm_stop_opaque;
2590 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
2593 vm_stop_opaque = opaque;
2597 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
2610 void vm_stop(int reason)
2613 cpu_disable_ticks();
2617 vm_stop_cb(vm_stop_opaque, reason);
2623 /* reset/shutdown handler */
2625 typedef struct QEMUResetEntry {
2626 QEMUResetHandler *func;
2628 struct QEMUResetEntry *next;
2631 static QEMUResetEntry *first_reset_entry;
2632 static int reset_requested;
2633 static int shutdown_requested;
2634 static int powerdown_requested;
2636 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
2638 QEMUResetEntry **pre, *re;
2640 pre = &first_reset_entry;
2641 while (*pre != NULL)
2642 pre = &(*pre)->next;
2643 re = qemu_mallocz(sizeof(QEMUResetEntry));
2645 re->opaque = opaque;
2650 void qemu_system_reset(void)
2654 /* reset all devices */
2655 for(re = first_reset_entry; re != NULL; re = re->next) {
2656 re->func(re->opaque);
2660 void qemu_system_reset_request(void)
2662 reset_requested = 1;
2663 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
2666 void qemu_system_shutdown_request(void)
2668 shutdown_requested = 1;
2669 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
2672 void qemu_system_powerdown_request(void)
2674 powerdown_requested = 1;
2675 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
2678 static void main_cpu_reset(void *opaque)
2680 #if defined(TARGET_I386) || defined(TARGET_SPARC)
2681 CPUState *env = opaque;
2686 void main_loop_wait(int timeout)
2689 struct pollfd ufds[MAX_IO_HANDLERS + 1], *pf;
2690 IOHandlerRecord *ioh, *ioh_next;
2700 /* poll any events */
2701 /* XXX: separate device handlers from system ones */
2703 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2704 if (!ioh->fd_can_read) {
2707 pf->events = POLLIN;
2711 max_size = ioh->fd_can_read(ioh->opaque);
2713 if (max_size > sizeof(buf))
2714 max_size = sizeof(buf);
2716 pf->events = POLLIN;
2723 ioh->max_size = max_size;
2726 ret = poll(ufds, pf - ufds, timeout);
2728 /* XXX: better handling of removal */
2729 for(ioh = first_io_handler; ioh != NULL; ioh = ioh_next) {
2730 ioh_next = ioh->next;
2733 if (pf->revents & POLLIN) {
2734 if (ioh->max_size == 0) {
2735 /* just a read event */
2736 ioh->fd_read(ioh->opaque, NULL, 0);
2738 n = read(ioh->fd, buf, ioh->max_size);
2740 ioh->fd_read(ioh->opaque, buf, n);
2741 } else if (errno != EAGAIN) {
2742 ioh->fd_read(ioh->opaque, NULL, -errno);
2749 #endif /* !defined(_WIN32) */
2750 #if defined(CONFIG_SLIRP)
2751 /* XXX: merge with poll() */
2753 fd_set rfds, wfds, xfds;
2761 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
2764 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
2766 slirp_select_poll(&rfds, &wfds, &xfds);
2772 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
2773 qemu_get_clock(vm_clock));
2774 /* run dma transfers, if any */
2778 /* real time timers */
2779 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
2780 qemu_get_clock(rt_clock));
2786 CPUState *env = global_env;
2790 ret = cpu_exec(env);
2791 if (shutdown_requested) {
2792 ret = EXCP_INTERRUPT;
2795 if (reset_requested) {
2796 reset_requested = 0;
2797 qemu_system_reset();
2798 ret = EXCP_INTERRUPT;
2800 if (powerdown_requested) {
2801 powerdown_requested = 0;
2802 qemu_system_powerdown();
2803 ret = EXCP_INTERRUPT;
2805 if (ret == EXCP_DEBUG) {
2806 vm_stop(EXCP_DEBUG);
2808 /* if hlt instruction, we wait until the next IRQ */
2809 /* XXX: use timeout computed from timers */
2810 if (ret == EXCP_HLT)
2817 main_loop_wait(timeout);
2819 cpu_disable_ticks();
2825 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2005 Fabrice Bellard\n"
2826 "usage: %s [options] [disk_image]\n"
2828 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
2830 "Standard options:\n"
2831 "-M machine select emulated machine (-M ? for list)\n"
2832 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
2833 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
2834 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
2835 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
2836 "-boot [a|c|d] boot on floppy (a), hard disk (c) or CD-ROM (d)\n"
2837 "-snapshot write to temporary files instead of disk image files\n"
2838 "-m megs set virtual RAM size to megs MB [default=%d]\n"
2839 "-nographic disable graphical output and redirect serial I/Os to console\n"
2841 "-k language use keyboard layout (for example \"fr\" for French)\n"
2844 "-enable-audio enable audio support\n"
2845 "-audio-help print list of audio drivers and their options\n"
2846 "-soundhw c1,... comma separated list of sound card names\n"
2847 " use -soundhw ? to get the list of supported sound cards\n"
2849 "-localtime set the real time clock to local time [default=utc]\n"
2850 "-full-screen start in full screen\n"
2852 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
2854 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
2855 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
2858 "Network options:\n"
2859 "-nics n simulate 'n' network cards [default=1]\n"
2860 "-macaddr addr set the mac address of the first interface\n"
2861 "-n script set tap/tun network init script [default=%s]\n"
2862 "-tun-fd fd use this fd as already opened tap/tun interface\n"
2864 "-user-net use user mode network stack [default if no tap/tun script]\n"
2865 "-tftp prefix allow tftp access to files starting with prefix [-user-net]\n"
2867 "-smb dir allow SMB access to files in 'dir' [-user-net]\n"
2869 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
2870 " redirect TCP or UDP connections from host to guest [-user-net]\n"
2872 "-dummy-net use dummy network stack\n"
2874 "Linux boot specific:\n"
2875 "-kernel bzImage use 'bzImage' as kernel image\n"
2876 "-append cmdline use 'cmdline' as kernel command line\n"
2877 "-initrd file use 'file' as initial ram disk\n"
2879 "Debug/Expert options:\n"
2880 "-monitor dev redirect the monitor to char device 'dev'\n"
2881 "-serial dev redirect the serial port to char device 'dev'\n"
2882 "-parallel dev redirect the parallel port to char device 'dev'\n"
2883 "-pidfile file Write PID to 'file'\n"
2884 "-S freeze CPU at startup (use 'c' to start execution)\n"
2885 "-s wait gdb connection to port %d\n"
2886 "-p port change gdb connection port\n"
2887 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
2888 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
2889 " translation (t=none or lba) (usually qemu can guess them)\n"
2890 "-L path set the directory for the BIOS and VGA BIOS\n"
2892 "-no-kqemu disable KQEMU kernel module usage\n"
2894 #ifdef USE_CODE_COPY
2895 "-no-code-copy disable code copy acceleration\n"
2898 "-isa simulate an ISA-only system (default is PCI system)\n"
2899 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
2900 " (default is CL-GD5446 PCI VGA)\n"
2902 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
2904 "During emulation, the following keys are useful:\n"
2905 "ctrl-alt-f toggle full screen\n"
2906 "ctrl-alt-n switch to virtual console 'n'\n"
2907 "ctrl-alt toggle mouse and keyboard grab\n"
2909 "When using -nographic, press 'ctrl-a h' to get some help.\n"
2911 #ifdef CONFIG_SOFTMMU
2917 DEFAULT_NETWORK_SCRIPT,
2918 DEFAULT_GDBSTUB_PORT,
2920 #ifndef CONFIG_SOFTMMU
2922 "NOTE: this version of QEMU is faster but it needs slightly patched OSes to\n"
2923 "work. Please use the 'qemu' executable to have a more accurate (but slower)\n"
2929 #define HAS_ARG 0x0001
2943 QEMU_OPTION_snapshot,
2945 QEMU_OPTION_nographic,
2947 QEMU_OPTION_enable_audio,
2948 QEMU_OPTION_audio_help,
2949 QEMU_OPTION_soundhw,
2953 QEMU_OPTION_macaddr,
2956 QEMU_OPTION_user_net,
2960 QEMU_OPTION_dummy_net,
2972 QEMU_OPTION_no_code_copy,
2977 QEMU_OPTION_localtime,
2978 QEMU_OPTION_cirrusvga,
2980 QEMU_OPTION_std_vga,
2981 QEMU_OPTION_monitor,
2983 QEMU_OPTION_parallel,
2985 QEMU_OPTION_full_screen,
2986 QEMU_OPTION_pidfile,
2987 QEMU_OPTION_no_kqemu,
2988 QEMU_OPTION_win2k_hack,
2991 typedef struct QEMUOption {
2997 const QEMUOption qemu_options[] = {
2998 { "h", 0, QEMU_OPTION_h },
3000 { "M", HAS_ARG, QEMU_OPTION_M },
3001 { "fda", HAS_ARG, QEMU_OPTION_fda },
3002 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
3003 { "hda", HAS_ARG, QEMU_OPTION_hda },
3004 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
3005 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
3006 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
3007 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
3008 { "boot", HAS_ARG, QEMU_OPTION_boot },
3009 { "snapshot", 0, QEMU_OPTION_snapshot },
3010 { "m", HAS_ARG, QEMU_OPTION_m },
3011 { "nographic", 0, QEMU_OPTION_nographic },
3012 { "k", HAS_ARG, QEMU_OPTION_k },
3014 { "enable-audio", 0, QEMU_OPTION_enable_audio },
3015 { "audio-help", 0, QEMU_OPTION_audio_help },
3016 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
3019 { "nics", HAS_ARG, QEMU_OPTION_nics},
3020 { "macaddr", HAS_ARG, QEMU_OPTION_macaddr},
3021 { "n", HAS_ARG, QEMU_OPTION_n },
3022 { "tun-fd", HAS_ARG, QEMU_OPTION_tun_fd },
3024 { "user-net", 0, QEMU_OPTION_user_net },
3025 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
3027 { "smb", HAS_ARG, QEMU_OPTION_smb },
3029 { "redir", HAS_ARG, QEMU_OPTION_redir },
3031 { "dummy-net", 0, QEMU_OPTION_dummy_net },
3033 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
3034 { "append", HAS_ARG, QEMU_OPTION_append },
3035 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
3037 { "S", 0, QEMU_OPTION_S },
3038 { "s", 0, QEMU_OPTION_s },
3039 { "p", HAS_ARG, QEMU_OPTION_p },
3040 { "d", HAS_ARG, QEMU_OPTION_d },
3041 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
3042 { "L", HAS_ARG, QEMU_OPTION_L },
3043 { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
3045 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
3048 { "prep", 0, QEMU_OPTION_prep },
3050 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
3051 { "g", 1, QEMU_OPTION_g },
3053 { "localtime", 0, QEMU_OPTION_localtime },
3054 { "isa", 0, QEMU_OPTION_isa },
3055 { "std-vga", 0, QEMU_OPTION_std_vga },
3056 { "monitor", 1, QEMU_OPTION_monitor },
3057 { "serial", 1, QEMU_OPTION_serial },
3058 { "parallel", 1, QEMU_OPTION_parallel },
3059 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
3060 { "full-screen", 0, QEMU_OPTION_full_screen },
3061 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
3062 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
3064 /* temporary options */
3065 { "pci", 0, QEMU_OPTION_pci },
3066 { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
3070 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
3072 /* this stack is only used during signal handling */
3073 #define SIGNAL_STACK_SIZE 32768
3075 static uint8_t *signal_stack;
3079 /* password input */
3081 static BlockDriverState *get_bdrv(int index)
3083 BlockDriverState *bs;
3086 bs = bs_table[index];
3087 } else if (index < 6) {
3088 bs = fd_table[index - 4];
3095 static void read_passwords(void)
3097 BlockDriverState *bs;
3101 for(i = 0; i < 6; i++) {
3103 if (bs && bdrv_is_encrypted(bs)) {
3104 term_printf("%s is encrypted.\n", bdrv_get_device_name(bs));
3105 for(j = 0; j < 3; j++) {
3106 monitor_readline("Password: ",
3107 1, password, sizeof(password));
3108 if (bdrv_set_key(bs, password) == 0)
3110 term_printf("invalid password\n");
3116 /* XXX: currently we cannot use simultaneously different CPUs */
3117 void register_machines(void)
3119 #if defined(TARGET_I386)
3120 qemu_register_machine(&pc_machine);
3121 #elif defined(TARGET_PPC)
3122 qemu_register_machine(&heathrow_machine);
3123 qemu_register_machine(&core99_machine);
3124 qemu_register_machine(&prep_machine);
3125 #elif defined(TARGET_MIPS)
3126 qemu_register_machine(&mips_machine);
3127 #elif defined(TARGET_SPARC)
3128 #ifdef TARGET_SPARC64
3129 qemu_register_machine(&sun4u_machine);
3131 qemu_register_machine(&sun4m_machine);
3137 static void select_soundhw (const char *optarg)
3139 if (*optarg == '?') {
3141 printf ("Valid sound card names (comma separated):\n");
3142 printf ("sb16 Creative Sound Blaster 16\n");
3145 printf ("adlib Ymaha YMF262 (OPL3)\n");
3147 printf ("adlib Ymaha YM3812 (OPL2)\n");
3151 printf ("gus Gravis Ultrasound GF1\n");
3153 printf ("es1370 ENSONIQ AudioPCI ES1370\n");
3154 exit (*optarg != '?');
3161 { "sb16", &sb16_enabled },
3163 { "adlib", &adlib_enabled },
3166 { "gus", &gus_enabled },
3168 { "es1370", &es1370_enabled },
3170 size_t tablen, l, i;
3176 tablen = sizeof (soundhw_tab) / sizeof (soundhw_tab[0]);
3179 e = strchr (p, ',');
3180 l = !e ? strlen (p) : (size_t) (e - p);
3181 for (i = 0; i < tablen; ++i) {
3182 if (!strncmp (soundhw_tab[i].name, p, l)) {
3184 *soundhw_tab[i].enabledp = 1;
3191 "Unknown sound card name (too big to show)\n");
3194 fprintf (stderr, "Unknown sound card name `%.*s'\n",
3199 p += l + (e != NULL);
3203 goto show_valid_cards;
3208 #define NET_IF_TUN 0
3209 #define NET_IF_USER 1
3210 #define NET_IF_DUMMY 2
3212 int main(int argc, char **argv)
3214 #ifdef CONFIG_GDBSTUB
3215 int use_gdbstub, gdbstub_port;
3218 int snapshot, linux_boot;
3220 const char *initrd_filename;
3221 const char *hd_filename[MAX_DISKS], *fd_filename[MAX_FD];
3222 const char *kernel_filename, *kernel_cmdline;
3223 DisplayState *ds = &display_state;
3224 int cyls, heads, secs, translation;
3225 int start_emulation = 1;
3227 int net_if_type, nb_tun_fds, tun_fds[MAX_NICS];
3229 const char *r, *optarg;
3230 CharDriverState *monitor_hd;
3231 char monitor_device[128];
3232 char serial_devices[MAX_SERIAL_PORTS][128];
3233 int serial_device_index;
3234 char parallel_devices[MAX_PARALLEL_PORTS][128];
3235 int parallel_device_index;
3236 const char *loadvm = NULL;
3237 QEMUMachine *machine;
3239 #if !defined(CONFIG_SOFTMMU)
3240 /* we never want that malloc() uses mmap() */
3241 mallopt(M_MMAP_THRESHOLD, 4096 * 1024);
3243 register_machines();
3244 machine = first_machine;
3245 initrd_filename = NULL;
3246 for(i = 0; i < MAX_FD; i++)
3247 fd_filename[i] = NULL;
3248 for(i = 0; i < MAX_DISKS; i++)
3249 hd_filename[i] = NULL;
3250 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
3251 vga_ram_size = VGA_RAM_SIZE;
3252 bios_size = BIOS_SIZE;
3253 pstrcpy(network_script, sizeof(network_script), DEFAULT_NETWORK_SCRIPT);
3254 #ifdef CONFIG_GDBSTUB
3256 gdbstub_port = DEFAULT_GDBSTUB_PORT;
3260 kernel_filename = NULL;
3261 kernel_cmdline = "";
3267 cyls = heads = secs = 0;
3268 translation = BIOS_ATA_TRANSLATION_AUTO;
3269 pstrcpy(monitor_device, sizeof(monitor_device), "vc");
3271 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
3272 for(i = 1; i < MAX_SERIAL_PORTS; i++)
3273 serial_devices[i][0] = '\0';
3274 serial_device_index = 0;
3276 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
3277 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
3278 parallel_devices[i][0] = '\0';
3279 parallel_device_index = 0;
3284 /* default mac address of the first network interface */
3298 hd_filename[0] = argv[optind++];
3300 const QEMUOption *popt;
3303 popt = qemu_options;
3306 fprintf(stderr, "%s: invalid option -- '%s'\n",
3310 if (!strcmp(popt->name, r + 1))
3314 if (popt->flags & HAS_ARG) {
3315 if (optind >= argc) {
3316 fprintf(stderr, "%s: option '%s' requires an argument\n",
3320 optarg = argv[optind++];
3325 switch(popt->index) {
3327 machine = find_machine(optarg);
3330 printf("Supported machines are:\n");
3331 for(m = first_machine; m != NULL; m = m->next) {
3332 printf("%-10s %s%s\n",
3334 m == first_machine ? " (default)" : "");
3339 case QEMU_OPTION_initrd:
3340 initrd_filename = optarg;
3342 case QEMU_OPTION_hda:
3343 case QEMU_OPTION_hdb:
3344 case QEMU_OPTION_hdc:
3345 case QEMU_OPTION_hdd:
3348 hd_index = popt->index - QEMU_OPTION_hda;
3349 hd_filename[hd_index] = optarg;
3350 if (hd_index == cdrom_index)
3354 case QEMU_OPTION_snapshot:
3357 case QEMU_OPTION_hdachs:
3361 cyls = strtol(p, (char **)&p, 0);
3362 if (cyls < 1 || cyls > 16383)
3367 heads = strtol(p, (char **)&p, 0);
3368 if (heads < 1 || heads > 16)
3373 secs = strtol(p, (char **)&p, 0);
3374 if (secs < 1 || secs > 63)
3378 if (!strcmp(p, "none"))
3379 translation = BIOS_ATA_TRANSLATION_NONE;
3380 else if (!strcmp(p, "lba"))
3381 translation = BIOS_ATA_TRANSLATION_LBA;
3382 else if (!strcmp(p, "auto"))
3383 translation = BIOS_ATA_TRANSLATION_AUTO;
3386 } else if (*p != '\0') {
3388 fprintf(stderr, "qemu: invalid physical CHS format\n");
3393 case QEMU_OPTION_nographic:
3394 pstrcpy(monitor_device, sizeof(monitor_device), "stdio");
3395 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "stdio");
3398 case QEMU_OPTION_kernel:
3399 kernel_filename = optarg;
3401 case QEMU_OPTION_append:
3402 kernel_cmdline = optarg;
3404 case QEMU_OPTION_tun_fd:
3408 net_if_type = NET_IF_TUN;
3409 if (nb_tun_fds < MAX_NICS) {
3410 fd = strtol(optarg, (char **)&p, 0);
3412 fprintf(stderr, "qemu: invalid fd for network interface %d\n", nb_tun_fds);
3415 tun_fds[nb_tun_fds++] = fd;
3419 case QEMU_OPTION_cdrom:
3420 if (cdrom_index >= 0) {
3421 hd_filename[cdrom_index] = optarg;
3424 case QEMU_OPTION_boot:
3425 boot_device = optarg[0];
3426 if (boot_device != 'a' &&
3429 boot_device != 'n' &&
3431 boot_device != 'c' && boot_device != 'd') {
3432 fprintf(stderr, "qemu: invalid boot device '%c'\n", boot_device);
3436 case QEMU_OPTION_fda:
3437 fd_filename[0] = optarg;
3439 case QEMU_OPTION_fdb:
3440 fd_filename[1] = optarg;
3442 case QEMU_OPTION_no_code_copy:
3443 code_copy_enabled = 0;
3445 case QEMU_OPTION_nics:
3446 nb_nics = atoi(optarg);
3447 if (nb_nics < 0 || nb_nics > MAX_NICS) {
3448 fprintf(stderr, "qemu: invalid number of network interfaces\n");
3452 case QEMU_OPTION_macaddr:
3457 for(i = 0; i < 6; i++) {
3458 macaddr[i] = strtol(p, (char **)&p, 16);
3465 fprintf(stderr, "qemu: invalid syntax for ethernet address\n");
3474 case QEMU_OPTION_tftp:
3475 tftp_prefix = optarg;
3478 case QEMU_OPTION_smb:
3479 net_slirp_smb(optarg);
3482 case QEMU_OPTION_user_net:
3483 net_if_type = NET_IF_USER;
3485 case QEMU_OPTION_redir:
3486 net_slirp_redir(optarg);
3489 case QEMU_OPTION_dummy_net:
3490 net_if_type = NET_IF_DUMMY;
3493 case QEMU_OPTION_enable_audio:
3500 case QEMU_OPTION_audio_help:
3504 case QEMU_OPTION_soundhw:
3505 select_soundhw (optarg);
3512 ram_size = atoi(optarg) * 1024 * 1024;
3515 if (ram_size > PHYS_RAM_MAX_SIZE) {
3516 fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
3517 PHYS_RAM_MAX_SIZE / (1024 * 1024));
3526 mask = cpu_str_to_log_mask(optarg);
3528 printf("Log items (comma separated):\n");
3529 for(item = cpu_log_items; item->mask != 0; item++) {
3530 printf("%-10s %s\n", item->name, item->help);
3538 pstrcpy(network_script, sizeof(network_script), optarg);
3540 #ifdef CONFIG_GDBSTUB
3545 gdbstub_port = atoi(optarg);
3552 start_emulation = 0;
3554 case QEMU_OPTION_pci:
3557 case QEMU_OPTION_isa:
3560 case QEMU_OPTION_prep:
3564 keyboard_layout = optarg;
3566 case QEMU_OPTION_localtime:
3569 case QEMU_OPTION_cirrusvga:
3570 cirrus_vga_enabled = 1;
3572 case QEMU_OPTION_std_vga:
3573 cirrus_vga_enabled = 0;
3580 w = strtol(p, (char **)&p, 10);
3583 fprintf(stderr, "qemu: invalid resolution or depth\n");
3589 h = strtol(p, (char **)&p, 10);
3594 depth = strtol(p, (char **)&p, 10);
3595 if (depth != 8 && depth != 15 && depth != 16 &&
3596 depth != 24 && depth != 32)
3598 } else if (*p == '\0') {
3599 depth = graphic_depth;
3606 graphic_depth = depth;
3609 case QEMU_OPTION_monitor:
3610 pstrcpy(monitor_device, sizeof(monitor_device), optarg);
3612 case QEMU_OPTION_serial:
3613 if (serial_device_index >= MAX_SERIAL_PORTS) {
3614 fprintf(stderr, "qemu: too many serial ports\n");
3617 pstrcpy(serial_devices[serial_device_index],
3618 sizeof(serial_devices[0]), optarg);
3619 serial_device_index++;
3621 case QEMU_OPTION_parallel:
3622 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
3623 fprintf(stderr, "qemu: too many parallel ports\n");
3626 pstrcpy(parallel_devices[parallel_device_index],
3627 sizeof(parallel_devices[0]), optarg);
3628 parallel_device_index++;
3630 case QEMU_OPTION_loadvm:
3633 case QEMU_OPTION_full_screen:
3636 case QEMU_OPTION_pidfile:
3637 create_pidfile(optarg);
3640 case QEMU_OPTION_win2k_hack:
3641 win2k_install_hack = 1;
3645 case QEMU_OPTION_no_kqemu:
3653 linux_boot = (kernel_filename != NULL);
3656 hd_filename[0] == '\0' &&
3657 (cdrom_index >= 0 && hd_filename[cdrom_index] == '\0') &&
3658 fd_filename[0] == '\0')
3661 /* boot to cd by default if no hard disk */
3662 if (hd_filename[0] == '\0' && boot_device == 'c') {
3663 if (fd_filename[0] != '\0')
3669 #if !defined(CONFIG_SOFTMMU)
3670 /* must avoid mmap() usage of glibc by setting a buffer "by hand" */
3672 static uint8_t stdout_buf[4096];
3673 setvbuf(stdout, stdout_buf, _IOLBF, sizeof(stdout_buf));
3676 setvbuf(stdout, NULL, _IOLBF, 0);
3679 /* init host network redirectors */
3680 if (net_if_type == -1) {
3681 net_if_type = NET_IF_TUN;
3682 #if defined(CONFIG_SLIRP)
3683 if (access(network_script, R_OK) < 0) {
3684 net_if_type = NET_IF_USER;
3689 for(i = 0; i < nb_nics; i++) {
3690 NetDriverState *nd = &nd_table[i];
3692 /* init virtual mac address */
3693 nd->macaddr[0] = macaddr[0];
3694 nd->macaddr[1] = macaddr[1];
3695 nd->macaddr[2] = macaddr[2];
3696 nd->macaddr[3] = macaddr[3];
3697 nd->macaddr[4] = macaddr[4];
3698 nd->macaddr[5] = macaddr[5] + i;
3699 switch(net_if_type) {
3700 #if defined(CONFIG_SLIRP)
3705 #if !defined(_WIN32)
3707 if (i < nb_tun_fds) {
3708 net_fd_init(nd, tun_fds[i]);
3710 if (net_tun_init(nd) < 0)
3722 /* init the memory */
3723 phys_ram_size = ram_size + vga_ram_size + bios_size;
3725 #ifdef CONFIG_SOFTMMU
3726 phys_ram_base = qemu_vmalloc(phys_ram_size);
3727 if (!phys_ram_base) {
3728 fprintf(stderr, "Could not allocate physical memory\n");
3732 /* as we must map the same page at several addresses, we must use
3737 tmpdir = getenv("QEMU_TMPDIR");
3740 snprintf(phys_ram_file, sizeof(phys_ram_file), "%s/vlXXXXXX", tmpdir);
3741 if (mkstemp(phys_ram_file) < 0) {
3742 fprintf(stderr, "Could not create temporary memory file '%s'\n",
3746 phys_ram_fd = open(phys_ram_file, O_CREAT | O_TRUNC | O_RDWR, 0600);
3747 if (phys_ram_fd < 0) {
3748 fprintf(stderr, "Could not open temporary memory file '%s'\n",
3752 ftruncate(phys_ram_fd, phys_ram_size);
3753 unlink(phys_ram_file);
3754 phys_ram_base = mmap(get_mmap_addr(phys_ram_size),
3756 PROT_WRITE | PROT_READ, MAP_SHARED | MAP_FIXED,
3758 if (phys_ram_base == MAP_FAILED) {
3759 fprintf(stderr, "Could not map physical memory\n");
3765 /* we always create the cdrom drive, even if no disk is there */
3767 if (cdrom_index >= 0) {
3768 bs_table[cdrom_index] = bdrv_new("cdrom");
3769 bdrv_set_type_hint(bs_table[cdrom_index], BDRV_TYPE_CDROM);
3772 /* open the virtual block devices */
3773 for(i = 0; i < MAX_DISKS; i++) {
3774 if (hd_filename[i]) {
3777 snprintf(buf, sizeof(buf), "hd%c", i + 'a');
3778 bs_table[i] = bdrv_new(buf);
3780 if (bdrv_open(bs_table[i], hd_filename[i], snapshot) < 0) {
3781 fprintf(stderr, "qemu: could not open hard disk image '%s'\n",
3785 if (i == 0 && cyls != 0) {
3786 bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
3787 bdrv_set_translation_hint(bs_table[i], translation);
3792 /* we always create at least one floppy disk */
3793 fd_table[0] = bdrv_new("fda");
3794 bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
3796 for(i = 0; i < MAX_FD; i++) {
3797 if (fd_filename[i]) {
3800 snprintf(buf, sizeof(buf), "fd%c", i + 'a');
3801 fd_table[i] = bdrv_new(buf);
3802 bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
3804 if (fd_filename[i] != '\0') {
3805 if (bdrv_open(fd_table[i], fd_filename[i], snapshot) < 0) {
3806 fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
3814 /* init CPU state */
3817 cpu_single_env = env;
3819 register_savevm("timer", 0, 1, timer_save, timer_load, env);
3820 register_savevm("cpu", 0, 3, cpu_save, cpu_load, env);
3821 register_savevm("ram", 0, 1, ram_save, ram_load, NULL);
3822 qemu_register_reset(main_cpu_reset, global_env);
3825 cpu_calibrate_ticks();
3829 dumb_display_init(ds);
3831 #if defined(CONFIG_SDL)
3832 sdl_display_init(ds, full_screen);
3833 #elif defined(CONFIG_COCOA)
3834 cocoa_display_init(ds, full_screen);
3836 dumb_display_init(ds);
3840 vga_console = graphic_console_init(ds);
3842 monitor_hd = qemu_chr_open(monitor_device);
3844 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
3847 monitor_init(monitor_hd, !nographic);
3849 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
3850 if (serial_devices[i][0] != '\0') {
3851 serial_hds[i] = qemu_chr_open(serial_devices[i]);
3852 if (!serial_hds[i]) {
3853 fprintf(stderr, "qemu: could not open serial device '%s'\n",
3857 if (!strcmp(serial_devices[i], "vc"))
3858 qemu_chr_printf(serial_hds[i], "serial%d console\n", i);
3862 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
3863 if (parallel_devices[i][0] != '\0') {
3864 parallel_hds[i] = qemu_chr_open(parallel_devices[i]);
3865 if (!parallel_hds[i]) {
3866 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
3867 parallel_devices[i]);
3870 if (!strcmp(parallel_devices[i], "vc"))
3871 qemu_chr_printf(parallel_hds[i], "parallel%d console\n", i);
3875 /* setup cpu signal handlers for MMU / self modifying code handling */
3876 #if !defined(CONFIG_SOFTMMU)
3878 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
3881 signal_stack = memalign(16, SIGNAL_STACK_SIZE);
3882 stk.ss_sp = signal_stack;
3883 stk.ss_size = SIGNAL_STACK_SIZE;
3886 if (sigaltstack(&stk, NULL) < 0) {
3887 perror("sigaltstack");
3893 struct sigaction act;
3895 sigfillset(&act.sa_mask);
3896 act.sa_flags = SA_SIGINFO;
3897 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
3898 act.sa_flags |= SA_ONSTACK;
3900 act.sa_sigaction = host_segv_handler;
3901 sigaction(SIGSEGV, &act, NULL);
3902 sigaction(SIGBUS, &act, NULL);
3903 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
3904 sigaction(SIGFPE, &act, NULL);
3911 struct sigaction act;
3912 sigfillset(&act.sa_mask);
3914 act.sa_handler = SIG_IGN;
3915 sigaction(SIGPIPE, &act, NULL);
3920 machine->init(ram_size, vga_ram_size, boot_device,
3921 ds, fd_filename, snapshot,
3922 kernel_filename, kernel_cmdline, initrd_filename);
3924 gui_timer = qemu_new_timer(rt_clock, gui_update, NULL);
3925 qemu_mod_timer(gui_timer, qemu_get_clock(rt_clock));
3927 #ifdef CONFIG_GDBSTUB
3929 if (gdbserver_start(gdbstub_port) < 0) {
3930 fprintf(stderr, "Could not open gdbserver socket on port %d\n",
3934 printf("Waiting gdb connection on port %d\n", gdbstub_port);
3939 qemu_loadvm(loadvm);
3942 /* XXX: simplify init */
3944 if (start_emulation) {