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;
159 uint32_t default_ioport_readb(void *opaque, uint32_t address)
161 #ifdef DEBUG_UNUSED_IOPORT
162 fprintf(stderr, "inb: port=0x%04x\n", address);
167 void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
169 #ifdef DEBUG_UNUSED_IOPORT
170 fprintf(stderr, "outb: port=0x%04x data=0x%02x\n", address, data);
174 /* default is to make two byte accesses */
175 uint32_t default_ioport_readw(void *opaque, uint32_t address)
178 data = ioport_read_table[0][address](ioport_opaque[address], address);
179 address = (address + 1) & (MAX_IOPORTS - 1);
180 data |= ioport_read_table[0][address](ioport_opaque[address], address) << 8;
184 void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
186 ioport_write_table[0][address](ioport_opaque[address], address, data & 0xff);
187 address = (address + 1) & (MAX_IOPORTS - 1);
188 ioport_write_table[0][address](ioport_opaque[address], address, (data >> 8) & 0xff);
191 uint32_t default_ioport_readl(void *opaque, uint32_t address)
193 #ifdef DEBUG_UNUSED_IOPORT
194 fprintf(stderr, "inl: port=0x%04x\n", address);
199 void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
201 #ifdef DEBUG_UNUSED_IOPORT
202 fprintf(stderr, "outl: port=0x%04x data=0x%02x\n", address, data);
206 void init_ioports(void)
210 for(i = 0; i < MAX_IOPORTS; i++) {
211 ioport_read_table[0][i] = default_ioport_readb;
212 ioport_write_table[0][i] = default_ioport_writeb;
213 ioport_read_table[1][i] = default_ioport_readw;
214 ioport_write_table[1][i] = default_ioport_writew;
215 ioport_read_table[2][i] = default_ioport_readl;
216 ioport_write_table[2][i] = default_ioport_writel;
220 /* size is the word size in byte */
221 int register_ioport_read(int start, int length, int size,
222 IOPortReadFunc *func, void *opaque)
228 } else if (size == 2) {
230 } else if (size == 4) {
233 hw_error("register_ioport_read: invalid size");
236 for(i = start; i < start + length; i += size) {
237 ioport_read_table[bsize][i] = func;
238 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
239 hw_error("register_ioport_read: invalid opaque");
240 ioport_opaque[i] = opaque;
245 /* size is the word size in byte */
246 int register_ioport_write(int start, int length, int size,
247 IOPortWriteFunc *func, void *opaque)
253 } else if (size == 2) {
255 } else if (size == 4) {
258 hw_error("register_ioport_write: invalid size");
261 for(i = start; i < start + length; i += size) {
262 ioport_write_table[bsize][i] = func;
263 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
264 hw_error("register_ioport_read: invalid opaque");
265 ioport_opaque[i] = opaque;
270 void isa_unassign_ioport(int start, int length)
274 for(i = start; i < start + length; i++) {
275 ioport_read_table[0][i] = default_ioport_readb;
276 ioport_read_table[1][i] = default_ioport_readw;
277 ioport_read_table[2][i] = default_ioport_readl;
279 ioport_write_table[0][i] = default_ioport_writeb;
280 ioport_write_table[1][i] = default_ioport_writew;
281 ioport_write_table[2][i] = default_ioport_writel;
285 /***********************************************************/
287 void pstrcpy(char *buf, int buf_size, const char *str)
297 if (c == 0 || q >= buf + buf_size - 1)
304 /* strcat and truncate. */
305 char *pstrcat(char *buf, int buf_size, const char *s)
310 pstrcpy(buf + len, buf_size - len, s);
314 int strstart(const char *str, const char *val, const char **ptr)
330 /* return the size or -1 if error */
331 int get_image_size(const char *filename)
334 fd = open(filename, O_RDONLY | O_BINARY);
337 size = lseek(fd, 0, SEEK_END);
342 /* return the size or -1 if error */
343 int load_image(const char *filename, uint8_t *addr)
346 fd = open(filename, O_RDONLY | O_BINARY);
349 size = lseek(fd, 0, SEEK_END);
350 lseek(fd, 0, SEEK_SET);
351 if (read(fd, addr, size) != size) {
359 void cpu_outb(CPUState *env, int addr, int val)
362 if (loglevel & CPU_LOG_IOPORT)
363 fprintf(logfile, "outb: %04x %02x\n", addr, val);
365 ioport_write_table[0][addr](ioport_opaque[addr], addr, val);
368 void cpu_outw(CPUState *env, int addr, int val)
371 if (loglevel & CPU_LOG_IOPORT)
372 fprintf(logfile, "outw: %04x %04x\n", addr, val);
374 ioport_write_table[1][addr](ioport_opaque[addr], addr, val);
377 void cpu_outl(CPUState *env, int addr, int val)
380 if (loglevel & CPU_LOG_IOPORT)
381 fprintf(logfile, "outl: %04x %08x\n", addr, val);
383 ioport_write_table[2][addr](ioport_opaque[addr], addr, val);
386 int cpu_inb(CPUState *env, int addr)
389 val = ioport_read_table[0][addr](ioport_opaque[addr], addr);
391 if (loglevel & CPU_LOG_IOPORT)
392 fprintf(logfile, "inb : %04x %02x\n", addr, val);
397 int cpu_inw(CPUState *env, int addr)
400 val = ioport_read_table[1][addr](ioport_opaque[addr], addr);
402 if (loglevel & CPU_LOG_IOPORT)
403 fprintf(logfile, "inw : %04x %04x\n", addr, val);
408 int cpu_inl(CPUState *env, int addr)
411 val = ioport_read_table[2][addr](ioport_opaque[addr], addr);
413 if (loglevel & CPU_LOG_IOPORT)
414 fprintf(logfile, "inl : %04x %08x\n", addr, val);
419 /***********************************************************/
420 void hw_error(const char *fmt, ...)
425 fprintf(stderr, "qemu: hardware error: ");
426 vfprintf(stderr, fmt, ap);
427 fprintf(stderr, "\n");
429 cpu_dump_state(global_env, stderr, fprintf, X86_DUMP_FPU | X86_DUMP_CCOP);
431 cpu_dump_state(global_env, stderr, fprintf, 0);
437 /***********************************************************/
440 static QEMUPutKBDEvent *qemu_put_kbd_event;
441 static void *qemu_put_kbd_event_opaque;
442 static QEMUPutMouseEvent *qemu_put_mouse_event;
443 static void *qemu_put_mouse_event_opaque;
445 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
447 qemu_put_kbd_event_opaque = opaque;
448 qemu_put_kbd_event = func;
451 void qemu_add_mouse_event_handler(QEMUPutMouseEvent *func, void *opaque)
453 qemu_put_mouse_event_opaque = opaque;
454 qemu_put_mouse_event = func;
457 void kbd_put_keycode(int keycode)
459 if (qemu_put_kbd_event) {
460 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
464 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
466 if (qemu_put_mouse_event) {
467 qemu_put_mouse_event(qemu_put_mouse_event_opaque,
468 dx, dy, dz, buttons_state);
472 /***********************************************************/
475 #if defined(__powerpc__)
477 static inline uint32_t get_tbl(void)
480 asm volatile("mftb %0" : "=r" (tbl));
484 static inline uint32_t get_tbu(void)
487 asm volatile("mftbu %0" : "=r" (tbl));
491 int64_t cpu_get_real_ticks(void)
494 /* NOTE: we test if wrapping has occurred */
500 return ((int64_t)h << 32) | l;
503 #elif defined(__i386__)
505 int64_t cpu_get_real_ticks(void)
508 asm volatile ("rdtsc" : "=A" (val));
512 #elif defined(__x86_64__)
514 int64_t cpu_get_real_ticks(void)
518 asm volatile("rdtsc" : "=a" (low), "=d" (high));
525 #elif defined(__ia64)
527 int64_t cpu_get_real_ticks(void)
530 asm volatile ("mov %0 = ar.itc" : "=r"(val) :: "memory");
535 #error unsupported CPU
538 static int64_t cpu_ticks_offset;
539 static int cpu_ticks_enabled;
541 static inline int64_t cpu_get_ticks(void)
543 if (!cpu_ticks_enabled) {
544 return cpu_ticks_offset;
546 return cpu_get_real_ticks() + cpu_ticks_offset;
550 /* enable cpu_get_ticks() */
551 void cpu_enable_ticks(void)
553 if (!cpu_ticks_enabled) {
554 cpu_ticks_offset -= cpu_get_real_ticks();
555 cpu_ticks_enabled = 1;
559 /* disable cpu_get_ticks() : the clock is stopped. You must not call
560 cpu_get_ticks() after that. */
561 void cpu_disable_ticks(void)
563 if (cpu_ticks_enabled) {
564 cpu_ticks_offset = cpu_get_ticks();
565 cpu_ticks_enabled = 0;
569 static int64_t get_clock(void)
574 return ((int64_t)tb.time * 1000 + (int64_t)tb.millitm) * 1000;
577 gettimeofday(&tv, NULL);
578 return tv.tv_sec * 1000000LL + tv.tv_usec;
582 void cpu_calibrate_ticks(void)
587 ticks = cpu_get_real_ticks();
593 usec = get_clock() - usec;
594 ticks = cpu_get_real_ticks() - ticks;
595 ticks_per_sec = (ticks * 1000000LL + (usec >> 1)) / usec;
598 /* compute with 96 bit intermediate result: (a*b)/c */
599 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
604 #ifdef WORDS_BIGENDIAN
614 rl = (uint64_t)u.l.low * (uint64_t)b;
615 rh = (uint64_t)u.l.high * (uint64_t)b;
618 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
622 #define QEMU_TIMER_REALTIME 0
623 #define QEMU_TIMER_VIRTUAL 1
627 /* XXX: add frequency */
635 struct QEMUTimer *next;
641 static QEMUTimer *active_timers[2];
643 static MMRESULT timerID;
645 /* frequency of the times() clock tick */
646 static int timer_freq;
649 QEMUClock *qemu_new_clock(int type)
652 clock = qemu_mallocz(sizeof(QEMUClock));
659 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
663 ts = qemu_mallocz(sizeof(QEMUTimer));
670 void qemu_free_timer(QEMUTimer *ts)
675 /* stop a timer, but do not dealloc it */
676 void qemu_del_timer(QEMUTimer *ts)
680 /* NOTE: this code must be signal safe because
681 qemu_timer_expired() can be called from a signal. */
682 pt = &active_timers[ts->clock->type];
695 /* modify the current timer so that it will be fired when current_time
696 >= expire_time. The corresponding callback will be called. */
697 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
703 /* add the timer in the sorted list */
704 /* NOTE: this code must be signal safe because
705 qemu_timer_expired() can be called from a signal. */
706 pt = &active_timers[ts->clock->type];
711 if (t->expire_time > expire_time)
715 ts->expire_time = expire_time;
720 int qemu_timer_pending(QEMUTimer *ts)
723 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
730 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
734 return (timer_head->expire_time <= current_time);
737 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
743 if (!ts || ts->expire_time > current_time)
745 /* remove timer from the list before calling the callback */
746 *ptimer_head = ts->next;
749 /* run the callback (the timer list can be modified) */
754 int64_t qemu_get_clock(QEMUClock *clock)
756 switch(clock->type) {
757 case QEMU_TIMER_REALTIME:
759 return GetTickCount();
764 /* Note that using gettimeofday() is not a good solution
765 for timers because its value change when the date is
767 if (timer_freq == 100) {
768 return times(&tp) * 10;
770 return ((int64_t)times(&tp) * 1000) / timer_freq;
775 case QEMU_TIMER_VIRTUAL:
776 return cpu_get_ticks();
781 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
783 uint64_t expire_time;
785 if (qemu_timer_pending(ts)) {
786 expire_time = ts->expire_time;
790 qemu_put_be64(f, expire_time);
793 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
795 uint64_t expire_time;
797 expire_time = qemu_get_be64(f);
798 if (expire_time != -1) {
799 qemu_mod_timer(ts, expire_time);
805 static void timer_save(QEMUFile *f, void *opaque)
807 if (cpu_ticks_enabled) {
808 hw_error("cannot save state if virtual timers are running");
810 qemu_put_be64s(f, &cpu_ticks_offset);
811 qemu_put_be64s(f, &ticks_per_sec);
814 static int timer_load(QEMUFile *f, void *opaque, int version_id)
818 if (cpu_ticks_enabled) {
821 qemu_get_be64s(f, &cpu_ticks_offset);
822 qemu_get_be64s(f, &ticks_per_sec);
827 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
828 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
830 static void host_alarm_handler(int host_signum)
834 #define DISP_FREQ 1000
836 static int64_t delta_min = INT64_MAX;
837 static int64_t delta_max, delta_cum, last_clock, delta, ti;
839 ti = qemu_get_clock(vm_clock);
840 if (last_clock != 0) {
841 delta = ti - last_clock;
842 if (delta < delta_min)
844 if (delta > delta_max)
847 if (++count == DISP_FREQ) {
848 printf("timer: min=%lld us max=%lld us avg=%lld us avg_freq=%0.3f Hz\n",
849 muldiv64(delta_min, 1000000, ticks_per_sec),
850 muldiv64(delta_max, 1000000, ticks_per_sec),
851 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
852 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
854 delta_min = INT64_MAX;
862 if (qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
863 qemu_get_clock(vm_clock)) ||
864 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
865 qemu_get_clock(rt_clock))) {
866 /* stop the cpu because a timer occured */
867 cpu_interrupt(global_env, CPU_INTERRUPT_EXIT);
873 #if defined(__linux__)
875 #define RTC_FREQ 1024
879 static int start_rtc_timer(void)
881 rtc_fd = open("/dev/rtc", O_RDONLY);
884 if (ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
885 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
886 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
887 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
890 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
895 pit_min_timer_count = PIT_FREQ / RTC_FREQ;
901 static int start_rtc_timer(void)
906 #endif /* !defined(__linux__) */
908 #endif /* !defined(_WIN32) */
910 static void init_timers(void)
912 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
913 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
918 timerID = timeSetEvent(10, // interval (ms)
920 host_alarm_handler, // function
921 (DWORD)&count, // user parameter
922 TIME_PERIODIC | TIME_CALLBACK_FUNCTION);
924 perror("failed timer alarm");
928 pit_min_timer_count = ((uint64_t)10000 * PIT_FREQ) / 1000000;
931 struct sigaction act;
932 struct itimerval itv;
934 /* get times() syscall frequency */
935 timer_freq = sysconf(_SC_CLK_TCK);
938 sigfillset(&act.sa_mask);
940 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
941 act.sa_flags |= SA_ONSTACK;
943 act.sa_handler = host_alarm_handler;
944 sigaction(SIGALRM, &act, NULL);
946 itv.it_interval.tv_sec = 0;
947 itv.it_interval.tv_usec = 999; /* for i386 kernel 2.6 to get 1 ms */
948 itv.it_value.tv_sec = 0;
949 itv.it_value.tv_usec = 10 * 1000;
950 setitimer(ITIMER_REAL, &itv, NULL);
951 /* we probe the tick duration of the kernel to inform the user if
952 the emulated kernel requested a too high timer frequency */
953 getitimer(ITIMER_REAL, &itv);
955 #if defined(__linux__)
956 if (itv.it_interval.tv_usec > 1000) {
957 /* try to use /dev/rtc to have a faster timer */
958 if (start_rtc_timer() < 0)
961 itv.it_interval.tv_sec = 0;
962 itv.it_interval.tv_usec = 0;
963 itv.it_value.tv_sec = 0;
964 itv.it_value.tv_usec = 0;
965 setitimer(ITIMER_REAL, &itv, NULL);
968 sigaction(SIGIO, &act, NULL);
969 fcntl(rtc_fd, F_SETFL, O_ASYNC);
970 fcntl(rtc_fd, F_SETOWN, getpid());
972 #endif /* defined(__linux__) */
975 pit_min_timer_count = ((uint64_t)itv.it_interval.tv_usec *
982 void quit_timers(void)
985 timeKillEvent(timerID);
989 /***********************************************************/
990 /* character device */
992 int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
994 return s->chr_write(s, buf, len);
997 void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1002 vsnprintf(buf, sizeof(buf), fmt, ap);
1003 qemu_chr_write(s, buf, strlen(buf));
1007 void qemu_chr_send_event(CharDriverState *s, int event)
1009 if (s->chr_send_event)
1010 s->chr_send_event(s, event);
1013 void qemu_chr_add_read_handler(CharDriverState *s,
1014 IOCanRWHandler *fd_can_read,
1015 IOReadHandler *fd_read, void *opaque)
1017 s->chr_add_read_handler(s, fd_can_read, fd_read, opaque);
1020 void qemu_chr_add_event_handler(CharDriverState *s, IOEventHandler *chr_event)
1022 s->chr_event = chr_event;
1025 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1030 static void null_chr_add_read_handler(CharDriverState *chr,
1031 IOCanRWHandler *fd_can_read,
1032 IOReadHandler *fd_read, void *opaque)
1036 CharDriverState *qemu_chr_open_null(void)
1038 CharDriverState *chr;
1040 chr = qemu_mallocz(sizeof(CharDriverState));
1043 chr->chr_write = null_chr_write;
1044 chr->chr_add_read_handler = null_chr_add_read_handler;
1052 /* for nographic stdio only */
1053 IOCanRWHandler *fd_can_read;
1054 IOReadHandler *fd_read;
1058 #define STDIO_MAX_CLIENTS 2
1060 static int stdio_nb_clients;
1061 static CharDriverState *stdio_clients[STDIO_MAX_CLIENTS];
1063 static int unix_write(int fd, const uint8_t *buf, int len1)
1069 ret = write(fd, buf, len);
1071 if (errno != EINTR && errno != EAGAIN)
1073 } else if (ret == 0) {
1083 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1085 FDCharDriver *s = chr->opaque;
1086 return unix_write(s->fd_out, buf, len);
1089 static void fd_chr_add_read_handler(CharDriverState *chr,
1090 IOCanRWHandler *fd_can_read,
1091 IOReadHandler *fd_read, void *opaque)
1093 FDCharDriver *s = chr->opaque;
1095 if (nographic && s->fd_in == 0) {
1096 s->fd_can_read = fd_can_read;
1097 s->fd_read = fd_read;
1098 s->fd_opaque = opaque;
1100 qemu_add_fd_read_handler(s->fd_in, fd_can_read, fd_read, opaque);
1104 /* open a character device to a unix fd */
1105 CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
1107 CharDriverState *chr;
1110 chr = qemu_mallocz(sizeof(CharDriverState));
1113 s = qemu_mallocz(sizeof(FDCharDriver));
1121 chr->chr_write = fd_chr_write;
1122 chr->chr_add_read_handler = fd_chr_add_read_handler;
1126 /* for STDIO, we handle the case where several clients use it
1129 #define TERM_ESCAPE 0x01 /* ctrl-a is used for escape */
1131 static int term_got_escape, client_index;
1133 void term_print_help(void)
1136 "C-a h print this help\n"
1137 "C-a x exit emulator\n"
1138 "C-a s save disk data back to file (if -snapshot)\n"
1139 "C-a b send break (magic sysrq)\n"
1140 "C-a c switch between console and monitor\n"
1141 "C-a C-a send C-a\n"
1145 /* called when a char is received */
1146 static void stdio_received_byte(int ch)
1148 if (term_got_escape) {
1149 term_got_escape = 0;
1160 for (i = 0; i < MAX_DISKS; i++) {
1162 bdrv_commit(bs_table[i]);
1167 if (client_index < stdio_nb_clients) {
1168 CharDriverState *chr;
1171 chr = stdio_clients[client_index];
1173 chr->chr_event(s->fd_opaque, CHR_EVENT_BREAK);
1178 if (client_index >= stdio_nb_clients)
1180 if (client_index == 0) {
1181 /* send a new line in the monitor to get the prompt */
1189 } else if (ch == TERM_ESCAPE) {
1190 term_got_escape = 1;
1193 if (client_index < stdio_nb_clients) {
1195 CharDriverState *chr;
1198 chr = stdio_clients[client_index];
1201 /* XXX: should queue the char if the device is not
1203 if (s->fd_can_read(s->fd_opaque) > 0)
1204 s->fd_read(s->fd_opaque, buf, 1);
1209 static int stdio_can_read(void *opaque)
1211 /* XXX: not strictly correct */
1215 static void stdio_read(void *opaque, const uint8_t *buf, int size)
1218 for(i = 0; i < size; i++)
1219 stdio_received_byte(buf[i]);
1222 /* init terminal so that we can grab keys */
1223 static struct termios oldtty;
1224 static int old_fd0_flags;
1226 static void term_exit(void)
1228 tcsetattr (0, TCSANOW, &oldtty);
1229 fcntl(0, F_SETFL, old_fd0_flags);
1232 static void term_init(void)
1236 tcgetattr (0, &tty);
1238 old_fd0_flags = fcntl(0, F_GETFL);
1240 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1241 |INLCR|IGNCR|ICRNL|IXON);
1242 tty.c_oflag |= OPOST;
1243 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1244 /* if graphical mode, we allow Ctrl-C handling */
1246 tty.c_lflag &= ~ISIG;
1247 tty.c_cflag &= ~(CSIZE|PARENB);
1250 tty.c_cc[VTIME] = 0;
1252 tcsetattr (0, TCSANOW, &tty);
1256 fcntl(0, F_SETFL, O_NONBLOCK);
1259 CharDriverState *qemu_chr_open_stdio(void)
1261 CharDriverState *chr;
1264 if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
1266 chr = qemu_chr_open_fd(0, 1);
1267 if (stdio_nb_clients == 0)
1268 qemu_add_fd_read_handler(0, stdio_can_read, stdio_read, NULL);
1269 client_index = stdio_nb_clients;
1271 if (stdio_nb_clients != 0)
1273 chr = qemu_chr_open_fd(0, 1);
1275 stdio_clients[stdio_nb_clients++] = chr;
1276 if (stdio_nb_clients == 1) {
1277 /* set the terminal in raw mode */
1283 #if defined(__linux__)
1284 CharDriverState *qemu_chr_open_pty(void)
1286 char slave_name[1024];
1287 int master_fd, slave_fd;
1289 /* Not satisfying */
1290 if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
1293 fprintf(stderr, "char device redirected to %s\n", slave_name);
1294 return qemu_chr_open_fd(master_fd, master_fd);
1297 CharDriverState *qemu_chr_open_pty(void)
1303 #endif /* !defined(_WIN32) */
1305 CharDriverState *qemu_chr_open(const char *filename)
1307 if (!strcmp(filename, "vc")) {
1308 return text_console_init(&display_state);
1309 } else if (!strcmp(filename, "null")) {
1310 return qemu_chr_open_null();
1313 if (!strcmp(filename, "pty")) {
1314 return qemu_chr_open_pty();
1315 } else if (!strcmp(filename, "stdio")) {
1316 return qemu_chr_open_stdio();
1324 /***********************************************************/
1325 /* Linux network device redirectors */
1327 void hex_dump(FILE *f, const uint8_t *buf, int size)
1331 for(i=0;i<size;i+=16) {
1335 fprintf(f, "%08x ", i);
1338 fprintf(f, " %02x", buf[i+j]);
1343 for(j=0;j<len;j++) {
1345 if (c < ' ' || c > '~')
1347 fprintf(f, "%c", c);
1353 void qemu_send_packet(NetDriverState *nd, const uint8_t *buf, int size)
1355 nd->send_packet(nd, buf, size);
1358 void qemu_add_read_packet(NetDriverState *nd, IOCanRWHandler *fd_can_read,
1359 IOReadHandler *fd_read, void *opaque)
1361 nd->add_read_packet(nd, fd_can_read, fd_read, opaque);
1364 /* dummy network adapter */
1366 static void dummy_send_packet(NetDriverState *nd, const uint8_t *buf, int size)
1370 static void dummy_add_read_packet(NetDriverState *nd,
1371 IOCanRWHandler *fd_can_read,
1372 IOReadHandler *fd_read, void *opaque)
1376 static int net_dummy_init(NetDriverState *nd)
1378 nd->send_packet = dummy_send_packet;
1379 nd->add_read_packet = dummy_add_read_packet;
1380 pstrcpy(nd->ifname, sizeof(nd->ifname), "dummy");
1384 #if defined(CONFIG_SLIRP)
1386 /* slirp network adapter */
1388 static void *slirp_fd_opaque;
1389 static IOCanRWHandler *slirp_fd_can_read;
1390 static IOReadHandler *slirp_fd_read;
1391 static int slirp_inited;
1393 int slirp_can_output(void)
1395 return slirp_fd_can_read(slirp_fd_opaque);
1398 void slirp_output(const uint8_t *pkt, int pkt_len)
1401 printf("output:\n");
1402 hex_dump(stdout, pkt, pkt_len);
1404 slirp_fd_read(slirp_fd_opaque, pkt, pkt_len);
1407 static void slirp_send_packet(NetDriverState *nd, const uint8_t *buf, int size)
1411 hex_dump(stdout, buf, size);
1413 slirp_input(buf, size);
1416 static void slirp_add_read_packet(NetDriverState *nd,
1417 IOCanRWHandler *fd_can_read,
1418 IOReadHandler *fd_read, void *opaque)
1420 slirp_fd_opaque = opaque;
1421 slirp_fd_can_read = fd_can_read;
1422 slirp_fd_read = fd_read;
1425 static int net_slirp_init(NetDriverState *nd)
1427 if (!slirp_inited) {
1431 nd->send_packet = slirp_send_packet;
1432 nd->add_read_packet = slirp_add_read_packet;
1433 pstrcpy(nd->ifname, sizeof(nd->ifname), "slirp");
1437 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
1442 p1 = strchr(p, sep);
1448 if (len > buf_size - 1)
1450 memcpy(buf, p, len);
1457 static void net_slirp_redir(const char *redir_str)
1462 struct in_addr guest_addr;
1463 int host_port, guest_port;
1465 if (!slirp_inited) {
1471 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
1473 if (!strcmp(buf, "tcp")) {
1475 } else if (!strcmp(buf, "udp")) {
1481 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
1483 host_port = strtol(buf, &r, 0);
1487 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
1489 if (buf[0] == '\0') {
1490 pstrcpy(buf, sizeof(buf), "10.0.2.15");
1492 if (!inet_aton(buf, &guest_addr))
1495 guest_port = strtol(p, &r, 0);
1499 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
1500 fprintf(stderr, "qemu: could not set up redirection\n");
1505 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
1513 static void smb_exit(void)
1517 char filename[1024];
1519 /* erase all the files in the directory */
1520 d = opendir(smb_dir);
1525 if (strcmp(de->d_name, ".") != 0 &&
1526 strcmp(de->d_name, "..") != 0) {
1527 snprintf(filename, sizeof(filename), "%s/%s",
1528 smb_dir, de->d_name);
1536 /* automatic user mode samba server configuration */
1537 void net_slirp_smb(const char *exported_dir)
1539 char smb_conf[1024];
1540 char smb_cmdline[1024];
1543 if (!slirp_inited) {
1548 /* XXX: better tmp dir construction */
1549 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
1550 if (mkdir(smb_dir, 0700) < 0) {
1551 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
1554 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
1556 f = fopen(smb_conf, "w");
1558 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
1565 "socket address=127.0.0.1\n"
1566 "pid directory=%s\n"
1567 "lock directory=%s\n"
1568 "log file=%s/log.smbd\n"
1569 "smb passwd file=%s/smbpasswd\n"
1570 "security = share\n"
1585 snprintf(smb_cmdline, sizeof(smb_cmdline), "/usr/sbin/smbd -s %s",
1588 slirp_add_exec(0, smb_cmdline, 4, 139);
1591 #endif /* !defined(_WIN32) */
1593 #endif /* CONFIG_SLIRP */
1595 #if !defined(_WIN32)
1597 static int tun_open(char *ifname, int ifname_size)
1603 fd = open("/dev/tap", O_RDWR);
1605 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
1610 dev = devname(s.st_rdev, S_IFCHR);
1611 pstrcpy(ifname, ifname_size, dev);
1613 fcntl(fd, F_SETFL, O_NONBLOCK);
1617 static int tun_open(char *ifname, int ifname_size)
1622 fd = open("/dev/net/tun", O_RDWR);
1624 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
1627 memset(&ifr, 0, sizeof(ifr));
1628 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
1629 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tun%d");
1630 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
1632 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
1636 printf("Connected to host network interface: %s\n", ifr.ifr_name);
1637 pstrcpy(ifname, ifname_size, ifr.ifr_name);
1638 fcntl(fd, F_SETFL, O_NONBLOCK);
1643 static void tun_send_packet(NetDriverState *nd, const uint8_t *buf, int size)
1645 write(nd->fd, buf, size);
1648 static void tun_add_read_packet(NetDriverState *nd,
1649 IOCanRWHandler *fd_can_read,
1650 IOReadHandler *fd_read, void *opaque)
1652 qemu_add_fd_read_handler(nd->fd, fd_can_read, fd_read, opaque);
1655 static int net_tun_init(NetDriverState *nd)
1661 nd->fd = tun_open(nd->ifname, sizeof(nd->ifname));
1665 /* try to launch network init script */
1670 *parg++ = network_script;
1671 *parg++ = nd->ifname;
1673 execv(network_script, args);
1676 while (waitpid(pid, &status, 0) != pid);
1677 if (!WIFEXITED(status) ||
1678 WEXITSTATUS(status) != 0) {
1679 fprintf(stderr, "%s: could not launch network script\n",
1683 nd->send_packet = tun_send_packet;
1684 nd->add_read_packet = tun_add_read_packet;
1688 static int net_fd_init(NetDriverState *nd, int fd)
1691 nd->send_packet = tun_send_packet;
1692 nd->add_read_packet = tun_add_read_packet;
1693 pstrcpy(nd->ifname, sizeof(nd->ifname), "tunfd");
1697 #endif /* !_WIN32 */
1699 /***********************************************************/
1702 static char *pid_filename;
1704 /* Remove PID file. Called on normal exit */
1706 static void remove_pidfile(void)
1708 unlink (pid_filename);
1711 static void create_pidfile(const char *filename)
1713 struct stat pidstat;
1716 /* Try to write our PID to the named file */
1717 if (stat(filename, &pidstat) < 0) {
1718 if (errno == ENOENT) {
1719 if ((f = fopen (filename, "w")) == NULL) {
1720 perror("Opening pidfile");
1723 fprintf(f, "%d\n", getpid());
1725 pid_filename = qemu_strdup(filename);
1726 if (!pid_filename) {
1727 fprintf(stderr, "Could not save PID filename");
1730 atexit(remove_pidfile);
1733 fprintf(stderr, "%s already exists. Remove it and try again.\n",
1739 /***********************************************************/
1742 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
1746 static void dumb_resize(DisplayState *ds, int w, int h)
1750 static void dumb_refresh(DisplayState *ds)
1752 vga_update_display();
1755 void dumb_display_init(DisplayState *ds)
1760 ds->dpy_update = dumb_update;
1761 ds->dpy_resize = dumb_resize;
1762 ds->dpy_refresh = dumb_refresh;
1765 #if !defined(CONFIG_SOFTMMU)
1766 /***********************************************************/
1767 /* cpu signal handler */
1768 static void host_segv_handler(int host_signum, siginfo_t *info,
1771 if (cpu_signal_handler(host_signum, info, puc))
1773 if (stdio_nb_clients > 0)
1779 /***********************************************************/
1782 #define MAX_IO_HANDLERS 64
1784 typedef struct IOHandlerRecord {
1786 IOCanRWHandler *fd_can_read;
1787 IOReadHandler *fd_read;
1789 /* temporary data */
1792 struct IOHandlerRecord *next;
1795 static IOHandlerRecord *first_io_handler;
1797 int qemu_add_fd_read_handler(int fd, IOCanRWHandler *fd_can_read,
1798 IOReadHandler *fd_read, void *opaque)
1800 IOHandlerRecord *ioh;
1802 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
1806 ioh->fd_can_read = fd_can_read;
1807 ioh->fd_read = fd_read;
1808 ioh->opaque = opaque;
1809 ioh->next = first_io_handler;
1810 first_io_handler = ioh;
1814 void qemu_del_fd_read_handler(int fd)
1816 IOHandlerRecord **pioh, *ioh;
1818 pioh = &first_io_handler;
1823 if (ioh->fd == fd) {
1831 /***********************************************************/
1832 /* savevm/loadvm support */
1834 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
1836 fwrite(buf, 1, size, f);
1839 void qemu_put_byte(QEMUFile *f, int v)
1844 void qemu_put_be16(QEMUFile *f, unsigned int v)
1846 qemu_put_byte(f, v >> 8);
1847 qemu_put_byte(f, v);
1850 void qemu_put_be32(QEMUFile *f, unsigned int v)
1852 qemu_put_byte(f, v >> 24);
1853 qemu_put_byte(f, v >> 16);
1854 qemu_put_byte(f, v >> 8);
1855 qemu_put_byte(f, v);
1858 void qemu_put_be64(QEMUFile *f, uint64_t v)
1860 qemu_put_be32(f, v >> 32);
1861 qemu_put_be32(f, v);
1864 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size)
1866 return fread(buf, 1, size, f);
1869 int qemu_get_byte(QEMUFile *f)
1879 unsigned int qemu_get_be16(QEMUFile *f)
1882 v = qemu_get_byte(f) << 8;
1883 v |= qemu_get_byte(f);
1887 unsigned int qemu_get_be32(QEMUFile *f)
1890 v = qemu_get_byte(f) << 24;
1891 v |= qemu_get_byte(f) << 16;
1892 v |= qemu_get_byte(f) << 8;
1893 v |= qemu_get_byte(f);
1897 uint64_t qemu_get_be64(QEMUFile *f)
1900 v = (uint64_t)qemu_get_be32(f) << 32;
1901 v |= qemu_get_be32(f);
1905 int64_t qemu_ftell(QEMUFile *f)
1910 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
1912 if (fseek(f, pos, whence) < 0)
1917 typedef struct SaveStateEntry {
1921 SaveStateHandler *save_state;
1922 LoadStateHandler *load_state;
1924 struct SaveStateEntry *next;
1927 static SaveStateEntry *first_se;
1929 int register_savevm(const char *idstr,
1932 SaveStateHandler *save_state,
1933 LoadStateHandler *load_state,
1936 SaveStateEntry *se, **pse;
1938 se = qemu_malloc(sizeof(SaveStateEntry));
1941 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
1942 se->instance_id = instance_id;
1943 se->version_id = version_id;
1944 se->save_state = save_state;
1945 se->load_state = load_state;
1946 se->opaque = opaque;
1949 /* add at the end of list */
1951 while (*pse != NULL)
1952 pse = &(*pse)->next;
1957 #define QEMU_VM_FILE_MAGIC 0x5145564d
1958 #define QEMU_VM_FILE_VERSION 0x00000001
1960 int qemu_savevm(const char *filename)
1964 int len, len_pos, cur_pos, saved_vm_running, ret;
1966 saved_vm_running = vm_running;
1969 f = fopen(filename, "wb");
1975 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
1976 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
1978 for(se = first_se; se != NULL; se = se->next) {
1980 len = strlen(se->idstr);
1981 qemu_put_byte(f, len);
1982 qemu_put_buffer(f, se->idstr, len);
1984 qemu_put_be32(f, se->instance_id);
1985 qemu_put_be32(f, se->version_id);
1987 /* record size: filled later */
1989 qemu_put_be32(f, 0);
1991 se->save_state(f, se->opaque);
1993 /* fill record size */
1995 len = ftell(f) - len_pos - 4;
1996 fseek(f, len_pos, SEEK_SET);
1997 qemu_put_be32(f, len);
1998 fseek(f, cur_pos, SEEK_SET);
2004 if (saved_vm_running)
2009 static SaveStateEntry *find_se(const char *idstr, int instance_id)
2013 for(se = first_se; se != NULL; se = se->next) {
2014 if (!strcmp(se->idstr, idstr) &&
2015 instance_id == se->instance_id)
2021 int qemu_loadvm(const char *filename)
2025 int len, cur_pos, ret, instance_id, record_len, version_id;
2026 int saved_vm_running;
2030 saved_vm_running = vm_running;
2033 f = fopen(filename, "rb");
2039 v = qemu_get_be32(f);
2040 if (v != QEMU_VM_FILE_MAGIC)
2042 v = qemu_get_be32(f);
2043 if (v != QEMU_VM_FILE_VERSION) {
2050 #if defined (DO_TB_FLUSH)
2051 tb_flush(global_env);
2053 len = qemu_get_byte(f);
2056 qemu_get_buffer(f, idstr, len);
2058 instance_id = qemu_get_be32(f);
2059 version_id = qemu_get_be32(f);
2060 record_len = qemu_get_be32(f);
2062 printf("idstr=%s instance=0x%x version=%d len=%d\n",
2063 idstr, instance_id, version_id, record_len);
2066 se = find_se(idstr, instance_id);
2068 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
2069 instance_id, idstr);
2071 ret = se->load_state(f, se->opaque, version_id);
2073 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
2074 instance_id, idstr);
2077 /* always seek to exact end of record */
2078 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
2083 if (saved_vm_running)
2088 /***********************************************************/
2089 /* cpu save/restore */
2091 #if defined(TARGET_I386)
2093 static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
2095 qemu_put_be32(f, dt->selector);
2096 qemu_put_betl(f, dt->base);
2097 qemu_put_be32(f, dt->limit);
2098 qemu_put_be32(f, dt->flags);
2101 static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
2103 dt->selector = qemu_get_be32(f);
2104 dt->base = qemu_get_betl(f);
2105 dt->limit = qemu_get_be32(f);
2106 dt->flags = qemu_get_be32(f);
2109 void cpu_save(QEMUFile *f, void *opaque)
2111 CPUState *env = opaque;
2112 uint16_t fptag, fpus, fpuc, fpregs_format;
2116 for(i = 0; i < CPU_NB_REGS; i++)
2117 qemu_put_betls(f, &env->regs[i]);
2118 qemu_put_betls(f, &env->eip);
2119 qemu_put_betls(f, &env->eflags);
2120 hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
2121 qemu_put_be32s(f, &hflags);
2125 fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
2127 for(i = 0; i < 8; i++) {
2128 fptag |= ((!env->fptags[i]) << i);
2131 qemu_put_be16s(f, &fpuc);
2132 qemu_put_be16s(f, &fpus);
2133 qemu_put_be16s(f, &fptag);
2135 #ifdef USE_X86LDOUBLE
2140 qemu_put_be16s(f, &fpregs_format);
2142 for(i = 0; i < 8; i++) {
2143 #ifdef USE_X86LDOUBLE
2147 /* we save the real CPU data (in case of MMX usage only 'mant'
2148 contains the MMX register */
2149 cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
2150 qemu_put_be64(f, mant);
2151 qemu_put_be16(f, exp);
2154 /* if we use doubles for float emulation, we save the doubles to
2155 avoid losing information in case of MMX usage. It can give
2156 problems if the image is restored on a CPU where long
2157 doubles are used instead. */
2158 qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
2162 for(i = 0; i < 6; i++)
2163 cpu_put_seg(f, &env->segs[i]);
2164 cpu_put_seg(f, &env->ldt);
2165 cpu_put_seg(f, &env->tr);
2166 cpu_put_seg(f, &env->gdt);
2167 cpu_put_seg(f, &env->idt);
2169 qemu_put_be32s(f, &env->sysenter_cs);
2170 qemu_put_be32s(f, &env->sysenter_esp);
2171 qemu_put_be32s(f, &env->sysenter_eip);
2173 qemu_put_betls(f, &env->cr[0]);
2174 qemu_put_betls(f, &env->cr[2]);
2175 qemu_put_betls(f, &env->cr[3]);
2176 qemu_put_betls(f, &env->cr[4]);
2178 for(i = 0; i < 8; i++)
2179 qemu_put_betls(f, &env->dr[i]);
2182 qemu_put_be32s(f, &env->a20_mask);
2185 qemu_put_be32s(f, &env->mxcsr);
2186 for(i = 0; i < CPU_NB_REGS; i++) {
2187 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
2188 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
2191 #ifdef TARGET_X86_64
2192 qemu_put_be64s(f, &env->efer);
2193 qemu_put_be64s(f, &env->star);
2194 qemu_put_be64s(f, &env->lstar);
2195 qemu_put_be64s(f, &env->cstar);
2196 qemu_put_be64s(f, &env->fmask);
2197 qemu_put_be64s(f, &env->kernelgsbase);
2201 #ifdef USE_X86LDOUBLE
2202 /* XXX: add that in a FPU generic layer */
2203 union x86_longdouble {
2208 #define MANTD1(fp) (fp & ((1LL << 52) - 1))
2209 #define EXPBIAS1 1023
2210 #define EXPD1(fp) ((fp >> 52) & 0x7FF)
2211 #define SIGND1(fp) ((fp >> 32) & 0x80000000)
2213 static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
2217 p->mant = (MANTD1(temp) << 11) | (1LL << 63);
2218 /* exponent + sign */
2219 e = EXPD1(temp) - EXPBIAS1 + 16383;
2220 e |= SIGND1(temp) >> 16;
2225 int cpu_load(QEMUFile *f, void *opaque, int version_id)
2227 CPUState *env = opaque;
2230 uint16_t fpus, fpuc, fptag, fpregs_format;
2232 if (version_id != 3)
2234 for(i = 0; i < CPU_NB_REGS; i++)
2235 qemu_get_betls(f, &env->regs[i]);
2236 qemu_get_betls(f, &env->eip);
2237 qemu_get_betls(f, &env->eflags);
2238 qemu_get_be32s(f, &hflags);
2240 qemu_get_be16s(f, &fpuc);
2241 qemu_get_be16s(f, &fpus);
2242 qemu_get_be16s(f, &fptag);
2243 qemu_get_be16s(f, &fpregs_format);
2245 /* NOTE: we cannot always restore the FPU state if the image come
2246 from a host with a different 'USE_X86LDOUBLE' define. We guess
2247 if we are in an MMX state to restore correctly in that case. */
2248 guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
2249 for(i = 0; i < 8; i++) {
2253 switch(fpregs_format) {
2255 mant = qemu_get_be64(f);
2256 exp = qemu_get_be16(f);
2257 #ifdef USE_X86LDOUBLE
2258 env->fpregs[i].d = cpu_set_fp80(mant, exp);
2260 /* difficult case */
2262 env->fpregs[i].mmx.MMX_Q(0) = mant;
2264 env->fpregs[i].d = cpu_set_fp80(mant, exp);
2268 mant = qemu_get_be64(f);
2269 #ifdef USE_X86LDOUBLE
2271 union x86_longdouble *p;
2272 /* difficult case */
2273 p = (void *)&env->fpregs[i];
2278 fp64_to_fp80(p, mant);
2282 env->fpregs[i].mmx.MMX_Q(0) = mant;
2291 /* XXX: restore FPU round state */
2292 env->fpstt = (fpus >> 11) & 7;
2293 env->fpus = fpus & ~0x3800;
2295 for(i = 0; i < 8; i++) {
2296 env->fptags[i] = (fptag >> i) & 1;
2299 for(i = 0; i < 6; i++)
2300 cpu_get_seg(f, &env->segs[i]);
2301 cpu_get_seg(f, &env->ldt);
2302 cpu_get_seg(f, &env->tr);
2303 cpu_get_seg(f, &env->gdt);
2304 cpu_get_seg(f, &env->idt);
2306 qemu_get_be32s(f, &env->sysenter_cs);
2307 qemu_get_be32s(f, &env->sysenter_esp);
2308 qemu_get_be32s(f, &env->sysenter_eip);
2310 qemu_get_betls(f, &env->cr[0]);
2311 qemu_get_betls(f, &env->cr[2]);
2312 qemu_get_betls(f, &env->cr[3]);
2313 qemu_get_betls(f, &env->cr[4]);
2315 for(i = 0; i < 8; i++)
2316 qemu_get_betls(f, &env->dr[i]);
2319 qemu_get_be32s(f, &env->a20_mask);
2321 qemu_get_be32s(f, &env->mxcsr);
2322 for(i = 0; i < CPU_NB_REGS; i++) {
2323 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
2324 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
2327 #ifdef TARGET_X86_64
2328 qemu_get_be64s(f, &env->efer);
2329 qemu_get_be64s(f, &env->star);
2330 qemu_get_be64s(f, &env->lstar);
2331 qemu_get_be64s(f, &env->cstar);
2332 qemu_get_be64s(f, &env->fmask);
2333 qemu_get_be64s(f, &env->kernelgsbase);
2336 /* XXX: compute hflags from scratch, except for CPL and IIF */
2337 env->hflags = hflags;
2342 #elif defined(TARGET_PPC)
2343 void cpu_save(QEMUFile *f, void *opaque)
2347 int cpu_load(QEMUFile *f, void *opaque, int version_id)
2352 #elif defined(TARGET_MIPS)
2353 void cpu_save(QEMUFile *f, void *opaque)
2357 int cpu_load(QEMUFile *f, void *opaque, int version_id)
2362 #elif defined(TARGET_SPARC)
2363 void cpu_save(QEMUFile *f, void *opaque)
2365 CPUState *env = opaque;
2369 for(i = 0; i < 8; i++)
2370 qemu_put_betls(f, &env->gregs[i]);
2371 for(i = 0; i < NWINDOWS * 16; i++)
2372 qemu_put_betls(f, &env->regbase[i]);
2375 for(i = 0; i < TARGET_FPREGS; i++) {
2381 qemu_put_betl(f, u.i);
2384 qemu_put_betls(f, &env->pc);
2385 qemu_put_betls(f, &env->npc);
2386 qemu_put_betls(f, &env->y);
2388 qemu_put_be32(f, tmp);
2389 qemu_put_betls(f, &env->fsr);
2390 qemu_put_betls(f, &env->tbr);
2391 #ifndef TARGET_SPARC64
2392 qemu_put_be32s(f, &env->wim);
2394 for(i = 0; i < 16; i++)
2395 qemu_put_be32s(f, &env->mmuregs[i]);
2399 int cpu_load(QEMUFile *f, void *opaque, int version_id)
2401 CPUState *env = opaque;
2405 for(i = 0; i < 8; i++)
2406 qemu_get_betls(f, &env->gregs[i]);
2407 for(i = 0; i < NWINDOWS * 16; i++)
2408 qemu_get_betls(f, &env->regbase[i]);
2411 for(i = 0; i < TARGET_FPREGS; i++) {
2416 u.i = qemu_get_betl(f);
2420 qemu_get_betls(f, &env->pc);
2421 qemu_get_betls(f, &env->npc);
2422 qemu_get_betls(f, &env->y);
2423 tmp = qemu_get_be32(f);
2424 env->cwp = 0; /* needed to ensure that the wrapping registers are
2425 correctly updated */
2427 qemu_get_betls(f, &env->fsr);
2428 qemu_get_betls(f, &env->tbr);
2429 #ifndef TARGET_SPARC64
2430 qemu_get_be32s(f, &env->wim);
2432 for(i = 0; i < 16; i++)
2433 qemu_get_be32s(f, &env->mmuregs[i]);
2440 #warning No CPU save/restore functions
2444 /***********************************************************/
2445 /* ram save/restore */
2447 /* we just avoid storing empty pages */
2448 static void ram_put_page(QEMUFile *f, const uint8_t *buf, int len)
2453 for(i = 1; i < len; i++) {
2457 qemu_put_byte(f, 1);
2458 qemu_put_byte(f, v);
2461 qemu_put_byte(f, 0);
2462 qemu_put_buffer(f, buf, len);
2465 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
2469 v = qemu_get_byte(f);
2472 if (qemu_get_buffer(f, buf, len) != len)
2476 v = qemu_get_byte(f);
2477 memset(buf, v, len);
2485 static void ram_save(QEMUFile *f, void *opaque)
2488 qemu_put_be32(f, phys_ram_size);
2489 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
2490 ram_put_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
2494 static int ram_load(QEMUFile *f, void *opaque, int version_id)
2498 if (version_id != 1)
2500 if (qemu_get_be32(f) != phys_ram_size)
2502 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
2503 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
2510 /***********************************************************/
2511 /* machine registration */
2513 QEMUMachine *first_machine = NULL;
2515 int qemu_register_machine(QEMUMachine *m)
2518 pm = &first_machine;
2526 QEMUMachine *find_machine(const char *name)
2530 for(m = first_machine; m != NULL; m = m->next) {
2531 if (!strcmp(m->name, name))
2537 /***********************************************************/
2538 /* main execution loop */
2540 void gui_update(void *opaque)
2542 display_state.dpy_refresh(&display_state);
2543 qemu_mod_timer(gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
2546 /* XXX: support several handlers */
2547 VMStopHandler *vm_stop_cb;
2548 VMStopHandler *vm_stop_opaque;
2550 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
2553 vm_stop_opaque = opaque;
2557 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
2570 void vm_stop(int reason)
2573 cpu_disable_ticks();
2577 vm_stop_cb(vm_stop_opaque, reason);
2583 /* reset/shutdown handler */
2585 typedef struct QEMUResetEntry {
2586 QEMUResetHandler *func;
2588 struct QEMUResetEntry *next;
2591 static QEMUResetEntry *first_reset_entry;
2592 static int reset_requested;
2593 static int shutdown_requested;
2594 static int powerdown_requested;
2596 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
2598 QEMUResetEntry **pre, *re;
2600 pre = &first_reset_entry;
2601 while (*pre != NULL)
2602 pre = &(*pre)->next;
2603 re = qemu_mallocz(sizeof(QEMUResetEntry));
2605 re->opaque = opaque;
2610 void qemu_system_reset(void)
2614 /* reset all devices */
2615 for(re = first_reset_entry; re != NULL; re = re->next) {
2616 re->func(re->opaque);
2620 void qemu_system_reset_request(void)
2622 reset_requested = 1;
2623 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
2626 void qemu_system_shutdown_request(void)
2628 shutdown_requested = 1;
2629 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
2632 void qemu_system_powerdown_request(void)
2634 powerdown_requested = 1;
2635 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
2638 static void main_cpu_reset(void *opaque)
2640 #if defined(TARGET_I386) || defined(TARGET_SPARC)
2641 CPUState *env = opaque;
2646 void main_loop_wait(int timeout)
2649 struct pollfd ufds[MAX_IO_HANDLERS + 1], *pf;
2650 IOHandlerRecord *ioh, *ioh_next;
2660 /* poll any events */
2661 /* XXX: separate device handlers from system ones */
2663 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2664 if (!ioh->fd_can_read) {
2667 pf->events = POLLIN;
2671 max_size = ioh->fd_can_read(ioh->opaque);
2673 if (max_size > sizeof(buf))
2674 max_size = sizeof(buf);
2676 pf->events = POLLIN;
2683 ioh->max_size = max_size;
2686 ret = poll(ufds, pf - ufds, timeout);
2688 /* XXX: better handling of removal */
2689 for(ioh = first_io_handler; ioh != NULL; ioh = ioh_next) {
2690 ioh_next = ioh->next;
2693 if (pf->revents & POLLIN) {
2694 if (ioh->max_size == 0) {
2695 /* just a read event */
2696 ioh->fd_read(ioh->opaque, NULL, 0);
2698 n = read(ioh->fd, buf, ioh->max_size);
2700 ioh->fd_read(ioh->opaque, buf, n);
2701 } else if (errno != EAGAIN) {
2702 ioh->fd_read(ioh->opaque, NULL, -errno);
2709 #endif /* !defined(_WIN32) */
2710 #if defined(CONFIG_SLIRP)
2711 /* XXX: merge with poll() */
2713 fd_set rfds, wfds, xfds;
2721 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
2724 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
2726 slirp_select_poll(&rfds, &wfds, &xfds);
2732 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
2733 qemu_get_clock(vm_clock));
2734 /* run dma transfers, if any */
2738 /* real time timers */
2739 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
2740 qemu_get_clock(rt_clock));
2746 CPUState *env = global_env;
2750 ret = cpu_exec(env);
2751 if (shutdown_requested) {
2752 ret = EXCP_INTERRUPT;
2755 if (reset_requested) {
2756 reset_requested = 0;
2757 qemu_system_reset();
2758 ret = EXCP_INTERRUPT;
2760 if (powerdown_requested) {
2761 powerdown_requested = 0;
2762 qemu_system_powerdown();
2763 ret = EXCP_INTERRUPT;
2765 if (ret == EXCP_DEBUG) {
2766 vm_stop(EXCP_DEBUG);
2768 /* if hlt instruction, we wait until the next IRQ */
2769 /* XXX: use timeout computed from timers */
2770 if (ret == EXCP_HLT)
2777 main_loop_wait(timeout);
2779 cpu_disable_ticks();
2785 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2004 Fabrice Bellard\n"
2786 "usage: %s [options] [disk_image]\n"
2788 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
2790 "Standard options:\n"
2791 "-M machine select emulated machine (-M ? for list)\n"
2792 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
2793 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
2794 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
2795 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
2796 "-boot [a|c|d] boot on floppy (a), hard disk (c) or CD-ROM (d)\n"
2797 "-snapshot write to temporary files instead of disk image files\n"
2798 "-m megs set virtual RAM size to megs MB [default=%d]\n"
2799 "-nographic disable graphical output and redirect serial I/Os to console\n"
2801 "-k language use keyboard layout (for example \"fr\" for French)\n"
2803 "-enable-audio enable audio support\n"
2804 "-localtime set the real time clock to local time [default=utc]\n"
2805 "-full-screen start in full screen\n"
2807 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
2809 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
2810 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
2813 "Network options:\n"
2814 "-nics n simulate 'n' network cards [default=1]\n"
2815 "-macaddr addr set the mac address of the first interface\n"
2816 "-n script set tap/tun network init script [default=%s]\n"
2817 "-tun-fd fd use this fd as already opened tap/tun interface\n"
2819 "-user-net use user mode network stack [default if no tap/tun script]\n"
2820 "-tftp prefix allow tftp access to files starting with prefix [-user-net]\n"
2822 "-smb dir allow SMB access to files in 'dir' [-user-net]\n"
2824 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
2825 " redirect TCP or UDP connections from host to guest [-user-net]\n"
2827 "-dummy-net use dummy network stack\n"
2829 "Linux boot specific:\n"
2830 "-kernel bzImage use 'bzImage' as kernel image\n"
2831 "-append cmdline use 'cmdline' as kernel command line\n"
2832 "-initrd file use 'file' as initial ram disk\n"
2834 "Debug/Expert options:\n"
2835 "-monitor dev redirect the monitor to char device 'dev'\n"
2836 "-serial dev redirect the serial port to char device 'dev'\n"
2837 "-parallel dev redirect the parallel port to char device 'dev'\n"
2838 "-pidfile file Write PID to 'file'\n"
2839 "-S freeze CPU at startup (use 'c' to start execution)\n"
2840 "-s wait gdb connection to port %d\n"
2841 "-p port change gdb connection port\n"
2842 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
2843 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
2844 " translation (t=none or lba) (usually qemu can guess them)\n"
2845 "-L path set the directory for the BIOS and VGA BIOS\n"
2847 "-no-kqemu disable KQEMU kernel module usage\n"
2849 #ifdef USE_CODE_COPY
2850 "-no-code-copy disable code copy acceleration\n"
2853 "-isa simulate an ISA-only system (default is PCI system)\n"
2854 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
2855 " (default is CL-GD5446 PCI VGA)\n"
2857 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
2859 "During emulation, the following keys are useful:\n"
2860 "ctrl-alt-f toggle full screen\n"
2861 "ctrl-alt-n switch to virtual console 'n'\n"
2862 "ctrl-alt toggle mouse and keyboard grab\n"
2864 "When using -nographic, press 'ctrl-a h' to get some help.\n"
2866 #ifdef CONFIG_SOFTMMU
2872 DEFAULT_NETWORK_SCRIPT,
2873 DEFAULT_GDBSTUB_PORT,
2875 #ifndef CONFIG_SOFTMMU
2877 "NOTE: this version of QEMU is faster but it needs slightly patched OSes to\n"
2878 "work. Please use the 'qemu' executable to have a more accurate (but slower)\n"
2884 #define HAS_ARG 0x0001
2898 QEMU_OPTION_snapshot,
2900 QEMU_OPTION_nographic,
2901 QEMU_OPTION_enable_audio,
2904 QEMU_OPTION_macaddr,
2907 QEMU_OPTION_user_net,
2911 QEMU_OPTION_dummy_net,
2923 QEMU_OPTION_no_code_copy,
2928 QEMU_OPTION_localtime,
2929 QEMU_OPTION_cirrusvga,
2931 QEMU_OPTION_std_vga,
2932 QEMU_OPTION_monitor,
2934 QEMU_OPTION_parallel,
2936 QEMU_OPTION_full_screen,
2937 QEMU_OPTION_pidfile,
2938 QEMU_OPTION_no_kqemu,
2939 QEMU_OPTION_win2k_hack,
2942 typedef struct QEMUOption {
2948 const QEMUOption qemu_options[] = {
2949 { "h", 0, QEMU_OPTION_h },
2951 { "M", HAS_ARG, QEMU_OPTION_M },
2952 { "fda", HAS_ARG, QEMU_OPTION_fda },
2953 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
2954 { "hda", HAS_ARG, QEMU_OPTION_hda },
2955 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
2956 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
2957 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
2958 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
2959 { "boot", HAS_ARG, QEMU_OPTION_boot },
2960 { "snapshot", 0, QEMU_OPTION_snapshot },
2961 { "m", HAS_ARG, QEMU_OPTION_m },
2962 { "nographic", 0, QEMU_OPTION_nographic },
2963 { "k", HAS_ARG, QEMU_OPTION_k },
2964 { "enable-audio", 0, QEMU_OPTION_enable_audio },
2966 { "nics", HAS_ARG, QEMU_OPTION_nics},
2967 { "macaddr", HAS_ARG, QEMU_OPTION_macaddr},
2968 { "n", HAS_ARG, QEMU_OPTION_n },
2969 { "tun-fd", HAS_ARG, QEMU_OPTION_tun_fd },
2971 { "user-net", 0, QEMU_OPTION_user_net },
2972 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
2974 { "smb", HAS_ARG, QEMU_OPTION_smb },
2976 { "redir", HAS_ARG, QEMU_OPTION_redir },
2978 { "dummy-net", 0, QEMU_OPTION_dummy_net },
2980 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
2981 { "append", HAS_ARG, QEMU_OPTION_append },
2982 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
2984 { "S", 0, QEMU_OPTION_S },
2985 { "s", 0, QEMU_OPTION_s },
2986 { "p", HAS_ARG, QEMU_OPTION_p },
2987 { "d", HAS_ARG, QEMU_OPTION_d },
2988 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
2989 { "L", HAS_ARG, QEMU_OPTION_L },
2990 { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
2992 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
2995 { "prep", 0, QEMU_OPTION_prep },
2997 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
2998 { "g", 1, QEMU_OPTION_g },
3000 { "localtime", 0, QEMU_OPTION_localtime },
3001 { "isa", 0, QEMU_OPTION_isa },
3002 { "std-vga", 0, QEMU_OPTION_std_vga },
3003 { "monitor", 1, QEMU_OPTION_monitor },
3004 { "serial", 1, QEMU_OPTION_serial },
3005 { "parallel", 1, QEMU_OPTION_parallel },
3006 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
3007 { "full-screen", 0, QEMU_OPTION_full_screen },
3008 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
3009 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
3011 /* temporary options */
3012 { "pci", 0, QEMU_OPTION_pci },
3013 { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
3017 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
3019 /* this stack is only used during signal handling */
3020 #define SIGNAL_STACK_SIZE 32768
3022 static uint8_t *signal_stack;
3026 /* password input */
3028 static BlockDriverState *get_bdrv(int index)
3030 BlockDriverState *bs;
3033 bs = bs_table[index];
3034 } else if (index < 6) {
3035 bs = fd_table[index - 4];
3042 static void read_passwords(void)
3044 BlockDriverState *bs;
3048 for(i = 0; i < 6; i++) {
3050 if (bs && bdrv_is_encrypted(bs)) {
3051 term_printf("%s is encrypted.\n", bdrv_get_device_name(bs));
3052 for(j = 0; j < 3; j++) {
3053 monitor_readline("Password: ",
3054 1, password, sizeof(password));
3055 if (bdrv_set_key(bs, password) == 0)
3057 term_printf("invalid password\n");
3063 /* XXX: currently we cannot use simultaneously different CPUs */
3064 void register_machines(void)
3066 #if defined(TARGET_I386)
3067 qemu_register_machine(&pc_machine);
3068 #elif defined(TARGET_PPC)
3069 qemu_register_machine(&heathrow_machine);
3070 qemu_register_machine(&core99_machine);
3071 qemu_register_machine(&prep_machine);
3072 #elif defined(TARGET_MIPS)
3073 qemu_register_machine(&mips_machine);
3074 #elif defined(TARGET_SPARC)
3075 #ifdef TARGET_SPARC64
3076 qemu_register_machine(&sun4u_machine);
3078 qemu_register_machine(&sun4m_machine);
3083 #define NET_IF_TUN 0
3084 #define NET_IF_USER 1
3085 #define NET_IF_DUMMY 2
3087 int main(int argc, char **argv)
3089 #ifdef CONFIG_GDBSTUB
3090 int use_gdbstub, gdbstub_port;
3093 int snapshot, linux_boot;
3095 const char *initrd_filename;
3096 const char *hd_filename[MAX_DISKS], *fd_filename[MAX_FD];
3097 const char *kernel_filename, *kernel_cmdline;
3098 DisplayState *ds = &display_state;
3099 int cyls, heads, secs, translation;
3100 int start_emulation = 1;
3102 int net_if_type, nb_tun_fds, tun_fds[MAX_NICS];
3104 const char *r, *optarg;
3105 CharDriverState *monitor_hd;
3106 char monitor_device[128];
3107 char serial_devices[MAX_SERIAL_PORTS][128];
3108 int serial_device_index;
3109 char parallel_devices[MAX_PARALLEL_PORTS][128];
3110 int parallel_device_index;
3111 const char *loadvm = NULL;
3112 QEMUMachine *machine;
3114 #if !defined(CONFIG_SOFTMMU)
3115 /* we never want that malloc() uses mmap() */
3116 mallopt(M_MMAP_THRESHOLD, 4096 * 1024);
3118 register_machines();
3119 machine = first_machine;
3120 initrd_filename = NULL;
3121 for(i = 0; i < MAX_FD; i++)
3122 fd_filename[i] = NULL;
3123 for(i = 0; i < MAX_DISKS; i++)
3124 hd_filename[i] = NULL;
3125 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
3126 vga_ram_size = VGA_RAM_SIZE;
3127 bios_size = BIOS_SIZE;
3128 pstrcpy(network_script, sizeof(network_script), DEFAULT_NETWORK_SCRIPT);
3129 #ifdef CONFIG_GDBSTUB
3131 gdbstub_port = DEFAULT_GDBSTUB_PORT;
3135 kernel_filename = NULL;
3136 kernel_cmdline = "";
3142 cyls = heads = secs = 0;
3143 translation = BIOS_ATA_TRANSLATION_AUTO;
3144 pstrcpy(monitor_device, sizeof(monitor_device), "vc");
3146 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
3147 for(i = 1; i < MAX_SERIAL_PORTS; i++)
3148 serial_devices[i][0] = '\0';
3149 serial_device_index = 0;
3151 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
3152 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
3153 parallel_devices[i][0] = '\0';
3154 parallel_device_index = 0;
3159 /* default mac address of the first network interface */
3173 hd_filename[0] = argv[optind++];
3175 const QEMUOption *popt;
3178 popt = qemu_options;
3181 fprintf(stderr, "%s: invalid option -- '%s'\n",
3185 if (!strcmp(popt->name, r + 1))
3189 if (popt->flags & HAS_ARG) {
3190 if (optind >= argc) {
3191 fprintf(stderr, "%s: option '%s' requires an argument\n",
3195 optarg = argv[optind++];
3200 switch(popt->index) {
3202 machine = find_machine(optarg);
3205 printf("Supported machines are:\n");
3206 for(m = first_machine; m != NULL; m = m->next) {
3207 printf("%-10s %s%s\n",
3209 m == first_machine ? " (default)" : "");
3214 case QEMU_OPTION_initrd:
3215 initrd_filename = optarg;
3217 case QEMU_OPTION_hda:
3218 case QEMU_OPTION_hdb:
3219 case QEMU_OPTION_hdc:
3220 case QEMU_OPTION_hdd:
3223 hd_index = popt->index - QEMU_OPTION_hda;
3224 hd_filename[hd_index] = optarg;
3225 if (hd_index == cdrom_index)
3229 case QEMU_OPTION_snapshot:
3232 case QEMU_OPTION_hdachs:
3236 cyls = strtol(p, (char **)&p, 0);
3237 if (cyls < 1 || cyls > 16383)
3242 heads = strtol(p, (char **)&p, 0);
3243 if (heads < 1 || heads > 16)
3248 secs = strtol(p, (char **)&p, 0);
3249 if (secs < 1 || secs > 63)
3253 if (!strcmp(p, "none"))
3254 translation = BIOS_ATA_TRANSLATION_NONE;
3255 else if (!strcmp(p, "lba"))
3256 translation = BIOS_ATA_TRANSLATION_LBA;
3257 else if (!strcmp(p, "auto"))
3258 translation = BIOS_ATA_TRANSLATION_AUTO;
3261 } else if (*p != '\0') {
3263 fprintf(stderr, "qemu: invalid physical CHS format\n");
3268 case QEMU_OPTION_nographic:
3269 pstrcpy(monitor_device, sizeof(monitor_device), "stdio");
3270 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "stdio");
3273 case QEMU_OPTION_kernel:
3274 kernel_filename = optarg;
3276 case QEMU_OPTION_append:
3277 kernel_cmdline = optarg;
3279 case QEMU_OPTION_tun_fd:
3283 net_if_type = NET_IF_TUN;
3284 if (nb_tun_fds < MAX_NICS) {
3285 fd = strtol(optarg, (char **)&p, 0);
3287 fprintf(stderr, "qemu: invalid fd for network interface %d\n", nb_tun_fds);
3290 tun_fds[nb_tun_fds++] = fd;
3294 case QEMU_OPTION_cdrom:
3295 if (cdrom_index >= 0) {
3296 hd_filename[cdrom_index] = optarg;
3299 case QEMU_OPTION_boot:
3300 boot_device = optarg[0];
3301 if (boot_device != 'a' &&
3304 boot_device != 'n' &&
3306 boot_device != 'c' && boot_device != 'd') {
3307 fprintf(stderr, "qemu: invalid boot device '%c'\n", boot_device);
3311 case QEMU_OPTION_fda:
3312 fd_filename[0] = optarg;
3314 case QEMU_OPTION_fdb:
3315 fd_filename[1] = optarg;
3317 case QEMU_OPTION_no_code_copy:
3318 code_copy_enabled = 0;
3320 case QEMU_OPTION_nics:
3321 nb_nics = atoi(optarg);
3322 if (nb_nics < 0 || nb_nics > MAX_NICS) {
3323 fprintf(stderr, "qemu: invalid number of network interfaces\n");
3327 case QEMU_OPTION_macaddr:
3332 for(i = 0; i < 6; i++) {
3333 macaddr[i] = strtol(p, (char **)&p, 16);
3340 fprintf(stderr, "qemu: invalid syntax for ethernet address\n");
3349 case QEMU_OPTION_tftp:
3350 tftp_prefix = optarg;
3353 case QEMU_OPTION_smb:
3354 net_slirp_smb(optarg);
3357 case QEMU_OPTION_user_net:
3358 net_if_type = NET_IF_USER;
3360 case QEMU_OPTION_redir:
3361 net_slirp_redir(optarg);
3364 case QEMU_OPTION_dummy_net:
3365 net_if_type = NET_IF_DUMMY;
3367 case QEMU_OPTION_enable_audio:
3374 ram_size = atoi(optarg) * 1024 * 1024;
3377 if (ram_size > PHYS_RAM_MAX_SIZE) {
3378 fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
3379 PHYS_RAM_MAX_SIZE / (1024 * 1024));
3388 mask = cpu_str_to_log_mask(optarg);
3390 printf("Log items (comma separated):\n");
3391 for(item = cpu_log_items; item->mask != 0; item++) {
3392 printf("%-10s %s\n", item->name, item->help);
3400 pstrcpy(network_script, sizeof(network_script), optarg);
3402 #ifdef CONFIG_GDBSTUB
3407 gdbstub_port = atoi(optarg);
3414 start_emulation = 0;
3416 case QEMU_OPTION_pci:
3419 case QEMU_OPTION_isa:
3422 case QEMU_OPTION_prep:
3426 keyboard_layout = optarg;
3428 case QEMU_OPTION_localtime:
3431 case QEMU_OPTION_cirrusvga:
3432 cirrus_vga_enabled = 1;
3434 case QEMU_OPTION_std_vga:
3435 cirrus_vga_enabled = 0;
3442 w = strtol(p, (char **)&p, 10);
3445 fprintf(stderr, "qemu: invalid resolution or depth\n");
3451 h = strtol(p, (char **)&p, 10);
3456 depth = strtol(p, (char **)&p, 10);
3457 if (depth != 8 && depth != 15 && depth != 16 &&
3458 depth != 24 && depth != 32)
3460 } else if (*p == '\0') {
3461 depth = graphic_depth;
3468 graphic_depth = depth;
3471 case QEMU_OPTION_monitor:
3472 pstrcpy(monitor_device, sizeof(monitor_device), optarg);
3474 case QEMU_OPTION_serial:
3475 if (serial_device_index >= MAX_SERIAL_PORTS) {
3476 fprintf(stderr, "qemu: too many serial ports\n");
3479 pstrcpy(serial_devices[serial_device_index],
3480 sizeof(serial_devices[0]), optarg);
3481 serial_device_index++;
3483 case QEMU_OPTION_parallel:
3484 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
3485 fprintf(stderr, "qemu: too many parallel ports\n");
3488 pstrcpy(parallel_devices[parallel_device_index],
3489 sizeof(parallel_devices[0]), optarg);
3490 parallel_device_index++;
3492 case QEMU_OPTION_loadvm:
3495 case QEMU_OPTION_full_screen:
3498 case QEMU_OPTION_pidfile:
3499 create_pidfile(optarg);
3502 case QEMU_OPTION_win2k_hack:
3503 win2k_install_hack = 1;
3507 case QEMU_OPTION_no_kqemu:
3515 linux_boot = (kernel_filename != NULL);
3518 hd_filename[0] == '\0' &&
3519 (cdrom_index >= 0 && hd_filename[cdrom_index] == '\0') &&
3520 fd_filename[0] == '\0')
3523 /* boot to cd by default if no hard disk */
3524 if (hd_filename[0] == '\0' && boot_device == 'c') {
3525 if (fd_filename[0] != '\0')
3531 #if !defined(CONFIG_SOFTMMU)
3532 /* must avoid mmap() usage of glibc by setting a buffer "by hand" */
3534 static uint8_t stdout_buf[4096];
3535 setvbuf(stdout, stdout_buf, _IOLBF, sizeof(stdout_buf));
3538 setvbuf(stdout, NULL, _IOLBF, 0);
3541 /* init host network redirectors */
3542 if (net_if_type == -1) {
3543 net_if_type = NET_IF_TUN;
3544 #if defined(CONFIG_SLIRP)
3545 if (access(network_script, R_OK) < 0) {
3546 net_if_type = NET_IF_USER;
3551 for(i = 0; i < nb_nics; i++) {
3552 NetDriverState *nd = &nd_table[i];
3554 /* init virtual mac address */
3555 nd->macaddr[0] = macaddr[0];
3556 nd->macaddr[1] = macaddr[1];
3557 nd->macaddr[2] = macaddr[2];
3558 nd->macaddr[3] = macaddr[3];
3559 nd->macaddr[4] = macaddr[4];
3560 nd->macaddr[5] = macaddr[5] + i;
3561 switch(net_if_type) {
3562 #if defined(CONFIG_SLIRP)
3567 #if !defined(_WIN32)
3569 if (i < nb_tun_fds) {
3570 net_fd_init(nd, tun_fds[i]);
3572 if (net_tun_init(nd) < 0)
3584 /* init the memory */
3585 phys_ram_size = ram_size + vga_ram_size + bios_size;
3587 #ifdef CONFIG_SOFTMMU
3588 phys_ram_base = qemu_vmalloc(phys_ram_size);
3589 if (!phys_ram_base) {
3590 fprintf(stderr, "Could not allocate physical memory\n");
3594 /* as we must map the same page at several addresses, we must use
3599 tmpdir = getenv("QEMU_TMPDIR");
3602 snprintf(phys_ram_file, sizeof(phys_ram_file), "%s/vlXXXXXX", tmpdir);
3603 if (mkstemp(phys_ram_file) < 0) {
3604 fprintf(stderr, "Could not create temporary memory file '%s'\n",
3608 phys_ram_fd = open(phys_ram_file, O_CREAT | O_TRUNC | O_RDWR, 0600);
3609 if (phys_ram_fd < 0) {
3610 fprintf(stderr, "Could not open temporary memory file '%s'\n",
3614 ftruncate(phys_ram_fd, phys_ram_size);
3615 unlink(phys_ram_file);
3616 phys_ram_base = mmap(get_mmap_addr(phys_ram_size),
3618 PROT_WRITE | PROT_READ, MAP_SHARED | MAP_FIXED,
3620 if (phys_ram_base == MAP_FAILED) {
3621 fprintf(stderr, "Could not map physical memory\n");
3627 /* we always create the cdrom drive, even if no disk is there */
3629 if (cdrom_index >= 0) {
3630 bs_table[cdrom_index] = bdrv_new("cdrom");
3631 bdrv_set_type_hint(bs_table[cdrom_index], BDRV_TYPE_CDROM);
3634 /* open the virtual block devices */
3635 for(i = 0; i < MAX_DISKS; i++) {
3636 if (hd_filename[i]) {
3639 snprintf(buf, sizeof(buf), "hd%c", i + 'a');
3640 bs_table[i] = bdrv_new(buf);
3642 if (bdrv_open(bs_table[i], hd_filename[i], snapshot) < 0) {
3643 fprintf(stderr, "qemu: could not open hard disk image '%s'\n",
3647 if (i == 0 && cyls != 0) {
3648 bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
3649 bdrv_set_translation_hint(bs_table[i], translation);
3654 /* we always create at least one floppy disk */
3655 fd_table[0] = bdrv_new("fda");
3656 bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
3658 for(i = 0; i < MAX_FD; i++) {
3659 if (fd_filename[i]) {
3662 snprintf(buf, sizeof(buf), "fd%c", i + 'a');
3663 fd_table[i] = bdrv_new(buf);
3664 bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
3666 if (fd_filename[i] != '\0') {
3667 if (bdrv_open(fd_table[i], fd_filename[i], snapshot) < 0) {
3668 fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
3676 /* init CPU state */
3679 cpu_single_env = env;
3681 register_savevm("timer", 0, 1, timer_save, timer_load, env);
3682 register_savevm("cpu", 0, 3, cpu_save, cpu_load, env);
3683 register_savevm("ram", 0, 1, ram_save, ram_load, NULL);
3684 qemu_register_reset(main_cpu_reset, global_env);
3687 cpu_calibrate_ticks();
3691 dumb_display_init(ds);
3693 #if defined(CONFIG_SDL)
3694 sdl_display_init(ds, full_screen);
3695 #elif defined(CONFIG_COCOA)
3696 cocoa_display_init(ds, full_screen);
3698 dumb_display_init(ds);
3702 vga_console = graphic_console_init(ds);
3704 monitor_hd = qemu_chr_open(monitor_device);
3706 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
3709 monitor_init(monitor_hd, !nographic);
3711 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
3712 if (serial_devices[i][0] != '\0') {
3713 serial_hds[i] = qemu_chr_open(serial_devices[i]);
3714 if (!serial_hds[i]) {
3715 fprintf(stderr, "qemu: could not open serial device '%s'\n",
3719 if (!strcmp(serial_devices[i], "vc"))
3720 qemu_chr_printf(serial_hds[i], "serial%d console\n", i);
3724 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
3725 if (parallel_devices[i][0] != '\0') {
3726 parallel_hds[i] = qemu_chr_open(parallel_devices[i]);
3727 if (!parallel_hds[i]) {
3728 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
3729 parallel_devices[i]);
3732 if (!strcmp(parallel_devices[i], "vc"))
3733 qemu_chr_printf(parallel_hds[i], "parallel%d console\n", i);
3737 /* setup cpu signal handlers for MMU / self modifying code handling */
3738 #if !defined(CONFIG_SOFTMMU)
3740 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
3743 signal_stack = memalign(16, SIGNAL_STACK_SIZE);
3744 stk.ss_sp = signal_stack;
3745 stk.ss_size = SIGNAL_STACK_SIZE;
3748 if (sigaltstack(&stk, NULL) < 0) {
3749 perror("sigaltstack");
3755 struct sigaction act;
3757 sigfillset(&act.sa_mask);
3758 act.sa_flags = SA_SIGINFO;
3759 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
3760 act.sa_flags |= SA_ONSTACK;
3762 act.sa_sigaction = host_segv_handler;
3763 sigaction(SIGSEGV, &act, NULL);
3764 sigaction(SIGBUS, &act, NULL);
3765 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
3766 sigaction(SIGFPE, &act, NULL);
3773 struct sigaction act;
3774 sigfillset(&act.sa_mask);
3776 act.sa_handler = SIG_IGN;
3777 sigaction(SIGPIPE, &act, NULL);
3782 machine->init(ram_size, vga_ram_size, boot_device,
3783 ds, fd_filename, snapshot,
3784 kernel_filename, kernel_cmdline, initrd_filename);
3786 gui_timer = qemu_new_timer(rt_clock, gui_update, NULL);
3787 qemu_mod_timer(gui_timer, qemu_get_clock(rt_clock));
3789 #ifdef CONFIG_GDBSTUB
3791 if (gdbserver_start(gdbstub_port) < 0) {
3792 fprintf(stderr, "Could not open gdbserver socket on port %d\n",
3796 printf("Waiting gdb connection on port %d\n", gdbstub_port);
3801 qemu_loadvm(loadvm);
3804 /* XXX: simplify init */
3806 if (start_emulation) {