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>
51 #include <linux/if_tun.h>
54 #include <linux/rtc.h>
55 #include <linux/ppdev.h>
59 #if defined(CONFIG_SLIRP)
65 #include <sys/timeb.h>
67 #define getopt_long_only getopt_long
68 #define memalign(align, size) malloc(size)
75 #endif /* CONFIG_SDL */
79 #define main qemu_main
80 #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 void *ioport_opaque[MAX_IOPORTS];
111 IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
112 IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
113 BlockDriverState *bs_table[MAX_DISKS], *fd_table[MAX_FD];
116 static DisplayState display_state;
118 const char* keyboard_layout = NULL;
119 int64_t ticks_per_sec;
120 int boot_device = 'c';
122 int pit_min_timer_count = 0;
124 NICInfo nd_table[MAX_NICS];
125 QEMUTimer *gui_timer;
128 int audio_enabled = 0;
129 int sb16_enabled = 0;
130 int adlib_enabled = 0;
132 int es1370_enabled = 0;
135 int cirrus_vga_enabled = 1;
137 int graphic_width = 1024;
138 int graphic_height = 768;
140 int graphic_width = 800;
141 int graphic_height = 600;
143 int graphic_depth = 15;
145 TextConsole *vga_console;
146 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
147 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
149 int win2k_install_hack = 0;
152 USBPort *vm_usb_ports[MAX_VM_USB_PORTS];
153 USBDevice *vm_usb_hub;
154 static VLANState *first_vlan;
156 #if defined(TARGET_SPARC)
158 #elif defined(TARGET_I386)
164 /***********************************************************/
165 /* x86 ISA bus support */
167 target_phys_addr_t isa_mem_base = 0;
170 uint32_t default_ioport_readb(void *opaque, uint32_t address)
172 #ifdef DEBUG_UNUSED_IOPORT
173 fprintf(stderr, "inb: port=0x%04x\n", address);
178 void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
180 #ifdef DEBUG_UNUSED_IOPORT
181 fprintf(stderr, "outb: port=0x%04x data=0x%02x\n", address, data);
185 /* default is to make two byte accesses */
186 uint32_t default_ioport_readw(void *opaque, uint32_t address)
189 data = ioport_read_table[0][address](ioport_opaque[address], address);
190 address = (address + 1) & (MAX_IOPORTS - 1);
191 data |= ioport_read_table[0][address](ioport_opaque[address], address) << 8;
195 void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
197 ioport_write_table[0][address](ioport_opaque[address], address, data & 0xff);
198 address = (address + 1) & (MAX_IOPORTS - 1);
199 ioport_write_table[0][address](ioport_opaque[address], address, (data >> 8) & 0xff);
202 uint32_t default_ioport_readl(void *opaque, uint32_t address)
204 #ifdef DEBUG_UNUSED_IOPORT
205 fprintf(stderr, "inl: port=0x%04x\n", address);
210 void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
212 #ifdef DEBUG_UNUSED_IOPORT
213 fprintf(stderr, "outl: port=0x%04x data=0x%02x\n", address, data);
217 void init_ioports(void)
221 for(i = 0; i < MAX_IOPORTS; i++) {
222 ioport_read_table[0][i] = default_ioport_readb;
223 ioport_write_table[0][i] = default_ioport_writeb;
224 ioport_read_table[1][i] = default_ioport_readw;
225 ioport_write_table[1][i] = default_ioport_writew;
226 ioport_read_table[2][i] = default_ioport_readl;
227 ioport_write_table[2][i] = default_ioport_writel;
231 /* size is the word size in byte */
232 int register_ioport_read(int start, int length, int size,
233 IOPortReadFunc *func, void *opaque)
239 } else if (size == 2) {
241 } else if (size == 4) {
244 hw_error("register_ioport_read: invalid size");
247 for(i = start; i < start + length; i += size) {
248 ioport_read_table[bsize][i] = func;
249 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
250 hw_error("register_ioport_read: invalid opaque");
251 ioport_opaque[i] = opaque;
256 /* size is the word size in byte */
257 int register_ioport_write(int start, int length, int size,
258 IOPortWriteFunc *func, void *opaque)
264 } else if (size == 2) {
266 } else if (size == 4) {
269 hw_error("register_ioport_write: invalid size");
272 for(i = start; i < start + length; i += size) {
273 ioport_write_table[bsize][i] = func;
274 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
275 hw_error("register_ioport_read: invalid opaque");
276 ioport_opaque[i] = opaque;
281 void isa_unassign_ioport(int start, int length)
285 for(i = start; i < start + length; i++) {
286 ioport_read_table[0][i] = default_ioport_readb;
287 ioport_read_table[1][i] = default_ioport_readw;
288 ioport_read_table[2][i] = default_ioport_readl;
290 ioport_write_table[0][i] = default_ioport_writeb;
291 ioport_write_table[1][i] = default_ioport_writew;
292 ioport_write_table[2][i] = default_ioport_writel;
296 /***********************************************************/
298 void pstrcpy(char *buf, int buf_size, const char *str)
308 if (c == 0 || q >= buf + buf_size - 1)
315 /* strcat and truncate. */
316 char *pstrcat(char *buf, int buf_size, const char *s)
321 pstrcpy(buf + len, buf_size - len, s);
325 int strstart(const char *str, const char *val, const char **ptr)
341 /* return the size or -1 if error */
342 int get_image_size(const char *filename)
345 fd = open(filename, O_RDONLY | O_BINARY);
348 size = lseek(fd, 0, SEEK_END);
353 /* return the size or -1 if error */
354 int load_image(const char *filename, uint8_t *addr)
357 fd = open(filename, O_RDONLY | O_BINARY);
360 size = lseek(fd, 0, SEEK_END);
361 lseek(fd, 0, SEEK_SET);
362 if (read(fd, addr, size) != size) {
370 void cpu_outb(CPUState *env, int addr, int val)
373 if (loglevel & CPU_LOG_IOPORT)
374 fprintf(logfile, "outb: %04x %02x\n", addr, val);
376 ioport_write_table[0][addr](ioport_opaque[addr], addr, val);
379 void cpu_outw(CPUState *env, int addr, int val)
382 if (loglevel & CPU_LOG_IOPORT)
383 fprintf(logfile, "outw: %04x %04x\n", addr, val);
385 ioport_write_table[1][addr](ioport_opaque[addr], addr, val);
388 void cpu_outl(CPUState *env, int addr, int val)
391 if (loglevel & CPU_LOG_IOPORT)
392 fprintf(logfile, "outl: %04x %08x\n", addr, val);
394 ioport_write_table[2][addr](ioport_opaque[addr], addr, val);
397 int cpu_inb(CPUState *env, int addr)
400 val = ioport_read_table[0][addr](ioport_opaque[addr], addr);
402 if (loglevel & CPU_LOG_IOPORT)
403 fprintf(logfile, "inb : %04x %02x\n", addr, val);
408 int cpu_inw(CPUState *env, int addr)
411 val = ioport_read_table[1][addr](ioport_opaque[addr], addr);
413 if (loglevel & CPU_LOG_IOPORT)
414 fprintf(logfile, "inw : %04x %04x\n", addr, val);
419 int cpu_inl(CPUState *env, int addr)
422 val = ioport_read_table[2][addr](ioport_opaque[addr], addr);
424 if (loglevel & CPU_LOG_IOPORT)
425 fprintf(logfile, "inl : %04x %08x\n", addr, val);
430 /***********************************************************/
431 void hw_error(const char *fmt, ...)
437 fprintf(stderr, "qemu: hardware error: ");
438 vfprintf(stderr, fmt, ap);
439 fprintf(stderr, "\n");
440 for(env = first_cpu; env != NULL; env = env->next_cpu) {
441 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
443 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
445 cpu_dump_state(env, stderr, fprintf, 0);
452 /***********************************************************/
455 static QEMUPutKBDEvent *qemu_put_kbd_event;
456 static void *qemu_put_kbd_event_opaque;
457 static QEMUPutMouseEvent *qemu_put_mouse_event;
458 static void *qemu_put_mouse_event_opaque;
460 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
462 qemu_put_kbd_event_opaque = opaque;
463 qemu_put_kbd_event = func;
466 void qemu_add_mouse_event_handler(QEMUPutMouseEvent *func, void *opaque)
468 qemu_put_mouse_event_opaque = opaque;
469 qemu_put_mouse_event = func;
472 void kbd_put_keycode(int keycode)
474 if (qemu_put_kbd_event) {
475 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
479 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
481 if (qemu_put_mouse_event) {
482 qemu_put_mouse_event(qemu_put_mouse_event_opaque,
483 dx, dy, dz, buttons_state);
487 /***********************************************************/
490 #if defined(__powerpc__)
492 static inline uint32_t get_tbl(void)
495 asm volatile("mftb %0" : "=r" (tbl));
499 static inline uint32_t get_tbu(void)
502 asm volatile("mftbu %0" : "=r" (tbl));
506 int64_t cpu_get_real_ticks(void)
509 /* NOTE: we test if wrapping has occurred */
515 return ((int64_t)h << 32) | l;
518 #elif defined(__i386__)
520 int64_t cpu_get_real_ticks(void)
523 asm volatile ("rdtsc" : "=A" (val));
527 #elif defined(__x86_64__)
529 int64_t cpu_get_real_ticks(void)
533 asm volatile("rdtsc" : "=a" (low), "=d" (high));
540 #elif defined(__ia64)
542 int64_t cpu_get_real_ticks(void)
545 asm volatile ("mov %0 = ar.itc" : "=r"(val) :: "memory");
549 #elif defined(__s390__)
551 int64_t cpu_get_real_ticks(void)
554 asm volatile("stck 0(%1)" : "=m" (val) : "a" (&val) : "cc");
559 #error unsupported CPU
562 static int64_t cpu_ticks_offset;
563 static int cpu_ticks_enabled;
565 static inline int64_t cpu_get_ticks(void)
567 if (!cpu_ticks_enabled) {
568 return cpu_ticks_offset;
570 return cpu_get_real_ticks() + cpu_ticks_offset;
574 /* enable cpu_get_ticks() */
575 void cpu_enable_ticks(void)
577 if (!cpu_ticks_enabled) {
578 cpu_ticks_offset -= cpu_get_real_ticks();
579 cpu_ticks_enabled = 1;
583 /* disable cpu_get_ticks() : the clock is stopped. You must not call
584 cpu_get_ticks() after that. */
585 void cpu_disable_ticks(void)
587 if (cpu_ticks_enabled) {
588 cpu_ticks_offset = cpu_get_ticks();
589 cpu_ticks_enabled = 0;
593 static int64_t get_clock(void)
598 return ((int64_t)tb.time * 1000 + (int64_t)tb.millitm) * 1000;
601 gettimeofday(&tv, NULL);
602 return tv.tv_sec * 1000000LL + tv.tv_usec;
606 void cpu_calibrate_ticks(void)
611 ticks = cpu_get_real_ticks();
617 usec = get_clock() - usec;
618 ticks = cpu_get_real_ticks() - ticks;
619 ticks_per_sec = (ticks * 1000000LL + (usec >> 1)) / usec;
622 /* compute with 96 bit intermediate result: (a*b)/c */
623 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
628 #ifdef WORDS_BIGENDIAN
638 rl = (uint64_t)u.l.low * (uint64_t)b;
639 rh = (uint64_t)u.l.high * (uint64_t)b;
642 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
646 #define QEMU_TIMER_REALTIME 0
647 #define QEMU_TIMER_VIRTUAL 1
651 /* XXX: add frequency */
659 struct QEMUTimer *next;
665 static QEMUTimer *active_timers[2];
667 static MMRESULT timerID;
669 /* frequency of the times() clock tick */
670 static int timer_freq;
673 QEMUClock *qemu_new_clock(int type)
676 clock = qemu_mallocz(sizeof(QEMUClock));
683 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
687 ts = qemu_mallocz(sizeof(QEMUTimer));
694 void qemu_free_timer(QEMUTimer *ts)
699 /* stop a timer, but do not dealloc it */
700 void qemu_del_timer(QEMUTimer *ts)
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];
719 /* modify the current timer so that it will be fired when current_time
720 >= expire_time. The corresponding callback will be called. */
721 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
727 /* add the timer in the sorted list */
728 /* NOTE: this code must be signal safe because
729 qemu_timer_expired() can be called from a signal. */
730 pt = &active_timers[ts->clock->type];
735 if (t->expire_time > expire_time)
739 ts->expire_time = expire_time;
744 int qemu_timer_pending(QEMUTimer *ts)
747 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
754 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
758 return (timer_head->expire_time <= current_time);
761 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
767 if (!ts || ts->expire_time > current_time)
769 /* remove timer from the list before calling the callback */
770 *ptimer_head = ts->next;
773 /* run the callback (the timer list can be modified) */
778 int64_t qemu_get_clock(QEMUClock *clock)
780 switch(clock->type) {
781 case QEMU_TIMER_REALTIME:
783 return GetTickCount();
788 /* Note that using gettimeofday() is not a good solution
789 for timers because its value change when the date is
791 if (timer_freq == 100) {
792 return times(&tp) * 10;
794 return ((int64_t)times(&tp) * 1000) / timer_freq;
799 case QEMU_TIMER_VIRTUAL:
800 return cpu_get_ticks();
805 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
807 uint64_t expire_time;
809 if (qemu_timer_pending(ts)) {
810 expire_time = ts->expire_time;
814 qemu_put_be64(f, expire_time);
817 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
819 uint64_t expire_time;
821 expire_time = qemu_get_be64(f);
822 if (expire_time != -1) {
823 qemu_mod_timer(ts, expire_time);
829 static void timer_save(QEMUFile *f, void *opaque)
831 if (cpu_ticks_enabled) {
832 hw_error("cannot save state if virtual timers are running");
834 qemu_put_be64s(f, &cpu_ticks_offset);
835 qemu_put_be64s(f, &ticks_per_sec);
838 static int timer_load(QEMUFile *f, void *opaque, int version_id)
842 if (cpu_ticks_enabled) {
845 qemu_get_be64s(f, &cpu_ticks_offset);
846 qemu_get_be64s(f, &ticks_per_sec);
851 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
852 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
854 static void host_alarm_handler(int host_signum)
858 #define DISP_FREQ 1000
860 static int64_t delta_min = INT64_MAX;
861 static int64_t delta_max, delta_cum, last_clock, delta, ti;
863 ti = qemu_get_clock(vm_clock);
864 if (last_clock != 0) {
865 delta = ti - last_clock;
866 if (delta < delta_min)
868 if (delta > delta_max)
871 if (++count == DISP_FREQ) {
872 printf("timer: min=%lld us max=%lld us avg=%lld us avg_freq=%0.3f Hz\n",
873 muldiv64(delta_min, 1000000, ticks_per_sec),
874 muldiv64(delta_max, 1000000, ticks_per_sec),
875 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
876 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
878 delta_min = INT64_MAX;
886 if (qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
887 qemu_get_clock(vm_clock)) ||
888 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
889 qemu_get_clock(rt_clock))) {
890 CPUState *env = cpu_single_env;
892 /* stop the currently executing cpu because a timer occured */
893 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
895 if (env->kqemu_enabled) {
896 kqemu_cpu_interrupt(env);
905 #if defined(__linux__)
907 #define RTC_FREQ 1024
911 static int start_rtc_timer(void)
913 rtc_fd = open("/dev/rtc", O_RDONLY);
916 if (ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
917 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
918 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
919 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
922 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
927 pit_min_timer_count = PIT_FREQ / RTC_FREQ;
933 static int start_rtc_timer(void)
938 #endif /* !defined(__linux__) */
940 #endif /* !defined(_WIN32) */
942 static void init_timers(void)
944 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
945 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
950 timerID = timeSetEvent(1, // interval (ms)
952 host_alarm_handler, // function
953 (DWORD)&count, // user parameter
954 TIME_PERIODIC | TIME_CALLBACK_FUNCTION);
956 perror("failed timer alarm");
960 pit_min_timer_count = ((uint64_t)10000 * PIT_FREQ) / 1000000;
963 struct sigaction act;
964 struct itimerval itv;
966 /* get times() syscall frequency */
967 timer_freq = sysconf(_SC_CLK_TCK);
970 sigfillset(&act.sa_mask);
972 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
973 act.sa_flags |= SA_ONSTACK;
975 act.sa_handler = host_alarm_handler;
976 sigaction(SIGALRM, &act, NULL);
978 itv.it_interval.tv_sec = 0;
979 itv.it_interval.tv_usec = 999; /* for i386 kernel 2.6 to get 1 ms */
980 itv.it_value.tv_sec = 0;
981 itv.it_value.tv_usec = 10 * 1000;
982 setitimer(ITIMER_REAL, &itv, NULL);
983 /* we probe the tick duration of the kernel to inform the user if
984 the emulated kernel requested a too high timer frequency */
985 getitimer(ITIMER_REAL, &itv);
987 #if defined(__linux__)
988 if (itv.it_interval.tv_usec > 1000) {
989 /* try to use /dev/rtc to have a faster timer */
990 if (start_rtc_timer() < 0)
993 itv.it_interval.tv_sec = 0;
994 itv.it_interval.tv_usec = 0;
995 itv.it_value.tv_sec = 0;
996 itv.it_value.tv_usec = 0;
997 setitimer(ITIMER_REAL, &itv, NULL);
1000 sigaction(SIGIO, &act, NULL);
1001 fcntl(rtc_fd, F_SETFL, O_ASYNC);
1002 fcntl(rtc_fd, F_SETOWN, getpid());
1004 #endif /* defined(__linux__) */
1007 pit_min_timer_count = ((uint64_t)itv.it_interval.tv_usec *
1008 PIT_FREQ) / 1000000;
1014 void quit_timers(void)
1017 timeKillEvent(timerID);
1021 /***********************************************************/
1022 /* character device */
1024 int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1026 return s->chr_write(s, buf, len);
1029 int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1033 return s->chr_ioctl(s, cmd, arg);
1036 void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1041 vsnprintf(buf, sizeof(buf), fmt, ap);
1042 qemu_chr_write(s, buf, strlen(buf));
1046 void qemu_chr_send_event(CharDriverState *s, int event)
1048 if (s->chr_send_event)
1049 s->chr_send_event(s, event);
1052 void qemu_chr_add_read_handler(CharDriverState *s,
1053 IOCanRWHandler *fd_can_read,
1054 IOReadHandler *fd_read, void *opaque)
1056 s->chr_add_read_handler(s, fd_can_read, fd_read, opaque);
1059 void qemu_chr_add_event_handler(CharDriverState *s, IOEventHandler *chr_event)
1061 s->chr_event = chr_event;
1064 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1069 static void null_chr_add_read_handler(CharDriverState *chr,
1070 IOCanRWHandler *fd_can_read,
1071 IOReadHandler *fd_read, void *opaque)
1075 CharDriverState *qemu_chr_open_null(void)
1077 CharDriverState *chr;
1079 chr = qemu_mallocz(sizeof(CharDriverState));
1082 chr->chr_write = null_chr_write;
1083 chr->chr_add_read_handler = null_chr_add_read_handler;
1091 IOCanRWHandler *fd_can_read;
1092 IOReadHandler *fd_read;
1097 #define STDIO_MAX_CLIENTS 2
1099 static int stdio_nb_clients;
1100 static CharDriverState *stdio_clients[STDIO_MAX_CLIENTS];
1102 static int unix_write(int fd, const uint8_t *buf, int len1)
1108 ret = write(fd, buf, len);
1110 if (errno != EINTR && errno != EAGAIN)
1112 } else if (ret == 0) {
1122 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1124 FDCharDriver *s = chr->opaque;
1125 return unix_write(s->fd_out, buf, len);
1128 static int fd_chr_read_poll(void *opaque)
1130 CharDriverState *chr = opaque;
1131 FDCharDriver *s = chr->opaque;
1133 s->max_size = s->fd_can_read(s->fd_opaque);
1137 static void fd_chr_read(void *opaque)
1139 CharDriverState *chr = opaque;
1140 FDCharDriver *s = chr->opaque;
1145 if (len > s->max_size)
1149 size = read(s->fd_in, buf, len);
1151 s->fd_read(s->fd_opaque, buf, size);
1155 static void fd_chr_add_read_handler(CharDriverState *chr,
1156 IOCanRWHandler *fd_can_read,
1157 IOReadHandler *fd_read, void *opaque)
1159 FDCharDriver *s = chr->opaque;
1161 if (s->fd_in >= 0) {
1162 s->fd_can_read = fd_can_read;
1163 s->fd_read = fd_read;
1164 s->fd_opaque = opaque;
1165 if (nographic && s->fd_in == 0) {
1167 qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
1168 fd_chr_read, NULL, chr);
1173 /* open a character device to a unix fd */
1174 CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
1176 CharDriverState *chr;
1179 chr = qemu_mallocz(sizeof(CharDriverState));
1182 s = qemu_mallocz(sizeof(FDCharDriver));
1190 chr->chr_write = fd_chr_write;
1191 chr->chr_add_read_handler = fd_chr_add_read_handler;
1195 CharDriverState *qemu_chr_open_file_out(const char *file_out)
1199 fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY);
1202 return qemu_chr_open_fd(-1, fd_out);
1205 CharDriverState *qemu_chr_open_pipe(const char *filename)
1209 fd = open(filename, O_RDWR | O_BINARY);
1212 return qemu_chr_open_fd(fd, fd);
1216 /* for STDIO, we handle the case where several clients use it
1219 #define TERM_ESCAPE 0x01 /* ctrl-a is used for escape */
1221 #define TERM_FIFO_MAX_SIZE 1
1223 static int term_got_escape, client_index;
1224 static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
1227 void term_print_help(void)
1230 "C-a h print this help\n"
1231 "C-a x exit emulator\n"
1232 "C-a s save disk data back to file (if -snapshot)\n"
1233 "C-a b send break (magic sysrq)\n"
1234 "C-a c switch between console and monitor\n"
1235 "C-a C-a send C-a\n"
1239 /* called when a char is received */
1240 static void stdio_received_byte(int ch)
1242 if (term_got_escape) {
1243 term_got_escape = 0;
1254 for (i = 0; i < MAX_DISKS; i++) {
1256 bdrv_commit(bs_table[i]);
1261 if (client_index < stdio_nb_clients) {
1262 CharDriverState *chr;
1265 chr = stdio_clients[client_index];
1267 chr->chr_event(s->fd_opaque, CHR_EVENT_BREAK);
1272 if (client_index >= stdio_nb_clients)
1274 if (client_index == 0) {
1275 /* send a new line in the monitor to get the prompt */
1283 } else if (ch == TERM_ESCAPE) {
1284 term_got_escape = 1;
1287 if (client_index < stdio_nb_clients) {
1289 CharDriverState *chr;
1292 chr = stdio_clients[client_index];
1294 if (s->fd_can_read(s->fd_opaque) > 0) {
1296 s->fd_read(s->fd_opaque, buf, 1);
1297 } else if (term_fifo_size == 0) {
1298 term_fifo[term_fifo_size++] = ch;
1304 static int stdio_read_poll(void *opaque)
1306 CharDriverState *chr;
1309 if (client_index < stdio_nb_clients) {
1310 chr = stdio_clients[client_index];
1312 /* try to flush the queue if needed */
1313 if (term_fifo_size != 0 && s->fd_can_read(s->fd_opaque) > 0) {
1314 s->fd_read(s->fd_opaque, term_fifo, 1);
1317 /* see if we can absorb more chars */
1318 if (term_fifo_size == 0)
1327 static void stdio_read(void *opaque)
1332 size = read(0, buf, 1);
1334 stdio_received_byte(buf[0]);
1337 /* init terminal so that we can grab keys */
1338 static struct termios oldtty;
1339 static int old_fd0_flags;
1341 static void term_exit(void)
1343 tcsetattr (0, TCSANOW, &oldtty);
1344 fcntl(0, F_SETFL, old_fd0_flags);
1347 static void term_init(void)
1351 tcgetattr (0, &tty);
1353 old_fd0_flags = fcntl(0, F_GETFL);
1355 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1356 |INLCR|IGNCR|ICRNL|IXON);
1357 tty.c_oflag |= OPOST;
1358 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1359 /* if graphical mode, we allow Ctrl-C handling */
1361 tty.c_lflag &= ~ISIG;
1362 tty.c_cflag &= ~(CSIZE|PARENB);
1365 tty.c_cc[VTIME] = 0;
1367 tcsetattr (0, TCSANOW, &tty);
1371 fcntl(0, F_SETFL, O_NONBLOCK);
1374 CharDriverState *qemu_chr_open_stdio(void)
1376 CharDriverState *chr;
1379 if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
1381 chr = qemu_chr_open_fd(0, 1);
1382 if (stdio_nb_clients == 0)
1383 qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, NULL);
1384 client_index = stdio_nb_clients;
1386 if (stdio_nb_clients != 0)
1388 chr = qemu_chr_open_fd(0, 1);
1390 stdio_clients[stdio_nb_clients++] = chr;
1391 if (stdio_nb_clients == 1) {
1392 /* set the terminal in raw mode */
1398 #if defined(__linux__)
1399 CharDriverState *qemu_chr_open_pty(void)
1401 char slave_name[1024];
1402 int master_fd, slave_fd;
1404 /* Not satisfying */
1405 if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
1408 fprintf(stderr, "char device redirected to %s\n", slave_name);
1409 return qemu_chr_open_fd(master_fd, master_fd);
1412 static void tty_serial_init(int fd, int speed,
1413 int parity, int data_bits, int stop_bits)
1419 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1420 speed, parity, data_bits, stop_bits);
1422 tcgetattr (fd, &tty);
1464 cfsetispeed(&tty, spd);
1465 cfsetospeed(&tty, spd);
1467 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1468 |INLCR|IGNCR|ICRNL|IXON);
1469 tty.c_oflag |= OPOST;
1470 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1471 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS);
1492 tty.c_cflag |= PARENB;
1495 tty.c_cflag |= PARENB | PARODD;
1499 tcsetattr (fd, TCSANOW, &tty);
1502 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1504 FDCharDriver *s = chr->opaque;
1507 case CHR_IOCTL_SERIAL_SET_PARAMS:
1509 QEMUSerialSetParams *ssp = arg;
1510 tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
1511 ssp->data_bits, ssp->stop_bits);
1514 case CHR_IOCTL_SERIAL_SET_BREAK:
1516 int enable = *(int *)arg;
1518 tcsendbreak(s->fd_in, 1);
1527 CharDriverState *qemu_chr_open_tty(const char *filename)
1529 CharDriverState *chr;
1532 fd = open(filename, O_RDWR | O_NONBLOCK);
1535 fcntl(fd, F_SETFL, O_NONBLOCK);
1536 tty_serial_init(fd, 115200, 'N', 8, 1);
1537 chr = qemu_chr_open_fd(fd, fd);
1540 chr->chr_ioctl = tty_serial_ioctl;
1544 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1546 int fd = (int)chr->opaque;
1550 case CHR_IOCTL_PP_READ_DATA:
1551 if (ioctl(fd, PPRDATA, &b) < 0)
1553 *(uint8_t *)arg = b;
1555 case CHR_IOCTL_PP_WRITE_DATA:
1556 b = *(uint8_t *)arg;
1557 if (ioctl(fd, PPWDATA, &b) < 0)
1560 case CHR_IOCTL_PP_READ_CONTROL:
1561 if (ioctl(fd, PPRCONTROL, &b) < 0)
1563 *(uint8_t *)arg = b;
1565 case CHR_IOCTL_PP_WRITE_CONTROL:
1566 b = *(uint8_t *)arg;
1567 if (ioctl(fd, PPWCONTROL, &b) < 0)
1570 case CHR_IOCTL_PP_READ_STATUS:
1571 if (ioctl(fd, PPRSTATUS, &b) < 0)
1573 *(uint8_t *)arg = b;
1581 CharDriverState *qemu_chr_open_pp(const char *filename)
1583 CharDriverState *chr;
1586 fd = open(filename, O_RDWR);
1590 if (ioctl(fd, PPCLAIM) < 0) {
1595 chr = qemu_mallocz(sizeof(CharDriverState));
1600 chr->opaque = (void *)fd;
1601 chr->chr_write = null_chr_write;
1602 chr->chr_add_read_handler = null_chr_add_read_handler;
1603 chr->chr_ioctl = pp_ioctl;
1608 CharDriverState *qemu_chr_open_pty(void)
1614 #endif /* !defined(_WIN32) */
1616 CharDriverState *qemu_chr_open(const char *filename)
1619 if (!strcmp(filename, "vc")) {
1620 return text_console_init(&display_state);
1621 } else if (!strcmp(filename, "null")) {
1622 return qemu_chr_open_null();
1625 if (strstart(filename, "file:", &p)) {
1626 return qemu_chr_open_file_out(p);
1627 } else if (strstart(filename, "pipe:", &p)) {
1628 return qemu_chr_open_pipe(p);
1629 } else if (!strcmp(filename, "pty")) {
1630 return qemu_chr_open_pty();
1631 } else if (!strcmp(filename, "stdio")) {
1632 return qemu_chr_open_stdio();
1635 #if defined(__linux__)
1636 if (strstart(filename, "/dev/parport", NULL)) {
1637 return qemu_chr_open_pp(filename);
1639 if (strstart(filename, "/dev/", NULL)) {
1640 return qemu_chr_open_tty(filename);
1648 /***********************************************************/
1649 /* network device redirectors */
1651 void hex_dump(FILE *f, const uint8_t *buf, int size)
1655 for(i=0;i<size;i+=16) {
1659 fprintf(f, "%08x ", i);
1662 fprintf(f, " %02x", buf[i+j]);
1667 for(j=0;j<len;j++) {
1669 if (c < ' ' || c > '~')
1671 fprintf(f, "%c", c);
1677 static int parse_macaddr(uint8_t *macaddr, const char *p)
1680 for(i = 0; i < 6; i++) {
1681 macaddr[i] = strtol(p, (char **)&p, 16);
1694 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
1699 p1 = strchr(p, sep);
1705 if (len > buf_size - 1)
1707 memcpy(buf, p, len);
1714 int parse_host_port(struct sockaddr_in *saddr, const char *str)
1722 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
1724 saddr->sin_family = AF_INET;
1725 if (buf[0] == '\0') {
1726 saddr->sin_addr.s_addr = 0;
1728 if (isdigit(buf[0])) {
1729 if (!inet_aton(buf, &saddr->sin_addr))
1735 if ((he = gethostbyname(buf)) == NULL)
1737 saddr->sin_addr = *(struct in_addr *)he->h_addr;
1741 port = strtol(p, (char **)&r, 0);
1744 saddr->sin_port = htons(port);
1748 /* find or alloc a new VLAN */
1749 VLANState *qemu_find_vlan(int id)
1751 VLANState **pvlan, *vlan;
1752 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
1756 vlan = qemu_mallocz(sizeof(VLANState));
1761 pvlan = &first_vlan;
1762 while (*pvlan != NULL)
1763 pvlan = &(*pvlan)->next;
1768 VLANClientState *qemu_new_vlan_client(VLANState *vlan,
1769 IOReadHandler *fd_read, void *opaque)
1771 VLANClientState *vc, **pvc;
1772 vc = qemu_mallocz(sizeof(VLANClientState));
1775 vc->fd_read = fd_read;
1776 vc->opaque = opaque;
1780 pvc = &vlan->first_client;
1781 while (*pvc != NULL)
1782 pvc = &(*pvc)->next;
1787 void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
1789 VLANState *vlan = vc1->vlan;
1790 VLANClientState *vc;
1793 printf("vlan %d send:\n", vlan->id);
1794 hex_dump(stdout, buf, size);
1796 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
1798 vc->fd_read(vc->opaque, buf, size);
1803 #if defined(CONFIG_SLIRP)
1805 /* slirp network adapter */
1807 static int slirp_inited;
1808 static VLANClientState *slirp_vc;
1810 int slirp_can_output(void)
1815 void slirp_output(const uint8_t *pkt, int pkt_len)
1818 printf("slirp output:\n");
1819 hex_dump(stdout, pkt, pkt_len);
1821 qemu_send_packet(slirp_vc, pkt, pkt_len);
1824 static void slirp_receive(void *opaque, const uint8_t *buf, int size)
1827 printf("slirp input:\n");
1828 hex_dump(stdout, buf, size);
1830 slirp_input(buf, size);
1833 static int net_slirp_init(VLANState *vlan)
1835 if (!slirp_inited) {
1839 slirp_vc = qemu_new_vlan_client(vlan,
1840 slirp_receive, NULL);
1841 snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
1845 static void net_slirp_redir(const char *redir_str)
1850 struct in_addr guest_addr;
1851 int host_port, guest_port;
1853 if (!slirp_inited) {
1859 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
1861 if (!strcmp(buf, "tcp")) {
1863 } else if (!strcmp(buf, "udp")) {
1869 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
1871 host_port = strtol(buf, &r, 0);
1875 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
1877 if (buf[0] == '\0') {
1878 pstrcpy(buf, sizeof(buf), "10.0.2.15");
1880 if (!inet_aton(buf, &guest_addr))
1883 guest_port = strtol(p, &r, 0);
1887 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
1888 fprintf(stderr, "qemu: could not set up redirection\n");
1893 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
1901 static void smb_exit(void)
1905 char filename[1024];
1907 /* erase all the files in the directory */
1908 d = opendir(smb_dir);
1913 if (strcmp(de->d_name, ".") != 0 &&
1914 strcmp(de->d_name, "..") != 0) {
1915 snprintf(filename, sizeof(filename), "%s/%s",
1916 smb_dir, de->d_name);
1924 /* automatic user mode samba server configuration */
1925 void net_slirp_smb(const char *exported_dir)
1927 char smb_conf[1024];
1928 char smb_cmdline[1024];
1931 if (!slirp_inited) {
1936 /* XXX: better tmp dir construction */
1937 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
1938 if (mkdir(smb_dir, 0700) < 0) {
1939 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
1942 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
1944 f = fopen(smb_conf, "w");
1946 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
1953 "socket address=127.0.0.1\n"
1954 "pid directory=%s\n"
1955 "lock directory=%s\n"
1956 "log file=%s/log.smbd\n"
1957 "smb passwd file=%s/smbpasswd\n"
1958 "security = share\n"
1973 snprintf(smb_cmdline, sizeof(smb_cmdline), "/usr/sbin/smbd -s %s",
1976 slirp_add_exec(0, smb_cmdline, 4, 139);
1979 #endif /* !defined(_WIN32) */
1981 #endif /* CONFIG_SLIRP */
1983 #if !defined(_WIN32)
1985 typedef struct TAPState {
1986 VLANClientState *vc;
1990 static void tap_receive(void *opaque, const uint8_t *buf, int size)
1992 TAPState *s = opaque;
1995 ret = write(s->fd, buf, size);
1996 if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
2003 static void tap_send(void *opaque)
2005 TAPState *s = opaque;
2009 size = read(s->fd, buf, sizeof(buf));
2011 qemu_send_packet(s->vc, buf, size);
2017 static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
2021 s = qemu_mallocz(sizeof(TAPState));
2025 s->vc = qemu_new_vlan_client(vlan, tap_receive, s);
2026 qemu_set_fd_handler(s->fd, tap_send, NULL, s);
2027 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
2032 static int tap_open(char *ifname, int ifname_size)
2038 fd = open("/dev/tap", O_RDWR);
2040 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
2045 dev = devname(s.st_rdev, S_IFCHR);
2046 pstrcpy(ifname, ifname_size, dev);
2048 fcntl(fd, F_SETFL, O_NONBLOCK);
2052 static int tap_open(char *ifname, int ifname_size)
2057 fd = open("/dev/net/tun", O_RDWR);
2059 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
2062 memset(&ifr, 0, sizeof(ifr));
2063 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
2064 if (ifname[0] != '\0')
2065 pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
2067 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
2068 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
2070 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
2074 pstrcpy(ifname, ifname_size, ifr.ifr_name);
2075 fcntl(fd, F_SETFL, O_NONBLOCK);
2080 static int net_tap_init(VLANState *vlan, const char *ifname1,
2081 const char *setup_script)
2084 int pid, status, fd;
2089 if (ifname1 != NULL)
2090 pstrcpy(ifname, sizeof(ifname), ifname1);
2093 fd = tap_open(ifname, sizeof(ifname));
2099 if (setup_script[0] != '\0') {
2100 /* try to launch network init script */
2105 *parg++ = (char *)setup_script;
2108 execv(setup_script, args);
2111 while (waitpid(pid, &status, 0) != pid);
2112 if (!WIFEXITED(status) ||
2113 WEXITSTATUS(status) != 0) {
2114 fprintf(stderr, "%s: could not launch network script\n",
2120 s = net_tap_fd_init(vlan, fd);
2123 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
2124 "tap: ifname=%s setup_script=%s", ifname, setup_script);
2128 /* network connection */
2129 typedef struct NetSocketState {
2130 VLANClientState *vc;
2132 int state; /* 0 = getting length, 1 = getting data */
2136 struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
2139 typedef struct NetSocketListenState {
2142 } NetSocketListenState;
2144 /* XXX: we consider we can send the whole packet without blocking */
2145 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
2147 NetSocketState *s = opaque;
2151 unix_write(s->fd, (const uint8_t *)&len, sizeof(len));
2152 unix_write(s->fd, buf, size);
2155 static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
2157 NetSocketState *s = opaque;
2158 sendto(s->fd, buf, size, 0,
2159 (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
2162 static void net_socket_send(void *opaque)
2164 NetSocketState *s = opaque;
2169 size = read(s->fd, buf1, sizeof(buf1));
2173 /* end of connection */
2174 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2179 /* reassemble a packet from the network */
2185 memcpy(s->buf + s->index, buf, l);
2189 if (s->index == 4) {
2191 s->packet_len = ntohl(*(uint32_t *)s->buf);
2197 l = s->packet_len - s->index;
2200 memcpy(s->buf + s->index, buf, l);
2204 if (s->index >= s->packet_len) {
2205 qemu_send_packet(s->vc, s->buf, s->packet_len);
2214 static void net_socket_send_dgram(void *opaque)
2216 NetSocketState *s = opaque;
2219 size = recv(s->fd, s->buf, sizeof(s->buf), 0);
2223 /* end of connection */
2224 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2227 qemu_send_packet(s->vc, s->buf, size);
2230 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
2235 if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
2236 fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
2237 inet_ntoa(mcastaddr->sin_addr), ntohl(mcastaddr->sin_addr.s_addr));
2241 fd = socket(PF_INET, SOCK_DGRAM, 0);
2243 perror("socket(PF_INET, SOCK_DGRAM)");
2247 /* Add host to multicast group */
2248 imr.imr_multiaddr = mcastaddr->sin_addr;
2249 imr.imr_interface.s_addr = htonl(INADDR_ANY);
2251 ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP, (void *) &imr, sizeof(struct ip_mreq));
2253 perror("setsockopt(IP_ADD_MEMBERSHIP)");
2257 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
2259 ret=setsockopt(fd, SOL_IP, IP_MULTICAST_LOOP, &val, sizeof(val));
2261 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
2265 ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val));
2267 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
2271 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
2277 fcntl(fd, F_SETFL, O_NONBLOCK);
2280 if (fd>=0) close(fd);
2284 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd,
2287 struct sockaddr_in saddr;
2289 socklen_t saddr_len;
2292 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
2293 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
2294 * by ONLY ONE process: we must "clone" this dgram socket --jjo
2298 if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
2300 if (saddr.sin_addr.s_addr==0) {
2301 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
2305 /* clone dgram socket */
2306 newfd = net_socket_mcast_create(&saddr);
2308 /* error already reported by net_socket_mcast_create() */
2312 /* clone newfd to fd, close newfd */
2317 fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
2318 fd, strerror(errno));
2323 s = qemu_mallocz(sizeof(NetSocketState));
2328 s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, s);
2329 qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
2331 /* mcast: save bound address as dst */
2332 if (is_connected) s->dgram_dst=saddr;
2334 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
2335 "socket: fd=%d (%s mcast=%s:%d)",
2336 fd, is_connected? "cloned" : "",
2337 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
2341 static void net_socket_connect(void *opaque)
2343 NetSocketState *s = opaque;
2344 qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
2347 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd,
2351 s = qemu_mallocz(sizeof(NetSocketState));
2355 s->vc = qemu_new_vlan_client(vlan,
2356 net_socket_receive, s);
2357 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
2358 "socket: fd=%d", fd);
2360 net_socket_connect(s);
2362 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
2367 static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
2370 int so_type=-1, optlen=sizeof(so_type);
2372 if(getsockopt(fd, SOL_SOCKET,SO_TYPE, &so_type, &optlen)< 0) {
2373 fprintf(stderr, "qemu: error: setsockopt(SO_TYPE) for fd=%d failed\n", fd);
2378 return net_socket_fd_init_dgram(vlan, fd, is_connected);
2380 return net_socket_fd_init_stream(vlan, fd, is_connected);
2382 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
2383 fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
2384 return net_socket_fd_init_stream(vlan, fd, is_connected);
2389 static void net_socket_accept(void *opaque)
2391 NetSocketListenState *s = opaque;
2393 struct sockaddr_in saddr;
2398 len = sizeof(saddr);
2399 fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
2400 if (fd < 0 && errno != EINTR) {
2402 } else if (fd >= 0) {
2406 s1 = net_socket_fd_init(s->vlan, fd, 1);
2410 snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
2411 "socket: connection from %s:%d",
2412 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
2416 static int net_socket_listen_init(VLANState *vlan, const char *host_str)
2418 NetSocketListenState *s;
2420 struct sockaddr_in saddr;
2422 if (parse_host_port(&saddr, host_str) < 0)
2425 s = qemu_mallocz(sizeof(NetSocketListenState));
2429 fd = socket(PF_INET, SOCK_STREAM, 0);
2434 fcntl(fd, F_SETFL, O_NONBLOCK);
2436 /* allow fast reuse */
2438 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val));
2440 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
2445 ret = listen(fd, 0);
2452 qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
2456 static int net_socket_connect_init(VLANState *vlan, const char *host_str)
2459 int fd, connected, ret;
2460 struct sockaddr_in saddr;
2462 if (parse_host_port(&saddr, host_str) < 0)
2465 fd = socket(PF_INET, SOCK_STREAM, 0);
2470 fcntl(fd, F_SETFL, O_NONBLOCK);
2474 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
2476 if (errno == EINTR || errno == EAGAIN) {
2477 } else if (errno == EINPROGRESS) {
2489 s = net_socket_fd_init(vlan, fd, connected);
2492 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
2493 "socket: connect to %s:%d",
2494 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
2498 static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
2502 struct sockaddr_in saddr;
2504 if (parse_host_port(&saddr, host_str) < 0)
2508 fd = net_socket_mcast_create(&saddr);
2512 s = net_socket_fd_init(vlan, fd, 0);
2516 s->dgram_dst = saddr;
2518 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
2519 "socket: mcast=%s:%d",
2520 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
2525 #endif /* !_WIN32 */
2527 static int get_param_value(char *buf, int buf_size,
2528 const char *tag, const char *str)
2537 while (*p != '\0' && *p != '=') {
2538 if ((q - option) < sizeof(option) - 1)
2546 if (!strcmp(tag, option)) {
2548 while (*p != '\0' && *p != ',') {
2549 if ((q - buf) < buf_size - 1)
2556 while (*p != '\0' && *p != ',') {
2567 int net_client_init(const char *str)
2578 while (*p != '\0' && *p != ',') {
2579 if ((q - device) < sizeof(device) - 1)
2587 if (get_param_value(buf, sizeof(buf), "vlan", p)) {
2588 vlan_id = strtol(buf, NULL, 0);
2590 vlan = qemu_find_vlan(vlan_id);
2592 fprintf(stderr, "Could not create vlan %d\n", vlan_id);
2595 if (!strcmp(device, "nic")) {
2599 if (nb_nics >= MAX_NICS) {
2600 fprintf(stderr, "Too Many NICs\n");
2603 nd = &nd_table[nb_nics];
2604 macaddr = nd->macaddr;
2610 macaddr[5] = 0x56 + nb_nics;
2612 if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
2613 if (parse_macaddr(macaddr, buf) < 0) {
2614 fprintf(stderr, "invalid syntax for ethernet address\n");
2622 if (!strcmp(device, "none")) {
2623 /* does nothing. It is needed to signal that no network cards
2628 if (!strcmp(device, "user")) {
2629 ret = net_slirp_init(vlan);
2633 if (!strcmp(device, "tap")) {
2635 char setup_script[1024];
2637 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
2638 fd = strtol(buf, NULL, 0);
2640 if (net_tap_fd_init(vlan, fd))
2643 get_param_value(ifname, sizeof(ifname), "ifname", p);
2644 if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
2645 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
2647 ret = net_tap_init(vlan, ifname, setup_script);
2650 if (!strcmp(device, "socket")) {
2651 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
2653 fd = strtol(buf, NULL, 0);
2655 if (net_socket_fd_init(vlan, fd, 1))
2657 } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
2658 ret = net_socket_listen_init(vlan, buf);
2659 } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
2660 ret = net_socket_connect_init(vlan, buf);
2661 } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
2662 ret = net_socket_mcast_init(vlan, buf);
2664 fprintf(stderr, "Unknown socket options: %s\n", p);
2670 fprintf(stderr, "Unknown network device: %s\n", device);
2674 fprintf(stderr, "Could not initialize device '%s'\n", device);
2680 void do_info_network(void)
2683 VLANClientState *vc;
2685 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
2686 term_printf("VLAN %d devices:\n", vlan->id);
2687 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
2688 term_printf(" %s\n", vc->info_str);
2692 /***********************************************************/
2695 static int usb_device_add(const char *devname)
2703 for(i = 0;i < MAX_VM_USB_PORTS; i++) {
2704 if (!vm_usb_ports[i]->dev)
2707 if (i == MAX_VM_USB_PORTS)
2710 if (strstart(devname, "host:", &p)) {
2711 dev = usb_host_device_open(p);
2714 } else if (!strcmp(devname, "mouse")) {
2715 dev = usb_mouse_init();
2721 usb_attach(vm_usb_ports[i], dev);
2725 static int usb_device_del(const char *devname)
2728 int bus_num, addr, i;
2734 p = strchr(devname, '.');
2737 bus_num = strtoul(devname, NULL, 0);
2738 addr = strtoul(p + 1, NULL, 0);
2741 for(i = 0;i < MAX_VM_USB_PORTS; i++) {
2742 dev = vm_usb_ports[i]->dev;
2743 if (dev && dev->addr == addr)
2746 if (i == MAX_VM_USB_PORTS)
2748 usb_attach(vm_usb_ports[i], NULL);
2752 void do_usb_add(const char *devname)
2755 ret = usb_device_add(devname);
2757 term_printf("Could not add USB device '%s'\n", devname);
2760 void do_usb_del(const char *devname)
2763 ret = usb_device_del(devname);
2765 term_printf("Could not remove USB device '%s'\n", devname);
2772 const char *speed_str;
2775 term_printf("USB support not enabled\n");
2779 for(i = 0; i < MAX_VM_USB_PORTS; i++) {
2780 dev = vm_usb_ports[i]->dev;
2782 term_printf("Hub port %d:\n", i);
2783 switch(dev->speed) {
2787 case USB_SPEED_FULL:
2790 case USB_SPEED_HIGH:
2797 term_printf(" Device %d.%d, speed %s Mb/s\n",
2798 0, dev->addr, speed_str);
2803 /***********************************************************/
2806 static char *pid_filename;
2808 /* Remove PID file. Called on normal exit */
2810 static void remove_pidfile(void)
2812 unlink (pid_filename);
2815 static void create_pidfile(const char *filename)
2817 struct stat pidstat;
2820 /* Try to write our PID to the named file */
2821 if (stat(filename, &pidstat) < 0) {
2822 if (errno == ENOENT) {
2823 if ((f = fopen (filename, "w")) == NULL) {
2824 perror("Opening pidfile");
2827 fprintf(f, "%d\n", getpid());
2829 pid_filename = qemu_strdup(filename);
2830 if (!pid_filename) {
2831 fprintf(stderr, "Could not save PID filename");
2834 atexit(remove_pidfile);
2837 fprintf(stderr, "%s already exists. Remove it and try again.\n",
2843 /***********************************************************/
2846 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
2850 static void dumb_resize(DisplayState *ds, int w, int h)
2854 static void dumb_refresh(DisplayState *ds)
2856 vga_update_display();
2859 void dumb_display_init(DisplayState *ds)
2864 ds->dpy_update = dumb_update;
2865 ds->dpy_resize = dumb_resize;
2866 ds->dpy_refresh = dumb_refresh;
2869 #if !defined(CONFIG_SOFTMMU)
2870 /***********************************************************/
2871 /* cpu signal handler */
2872 static void host_segv_handler(int host_signum, siginfo_t *info,
2875 if (cpu_signal_handler(host_signum, info, puc))
2877 if (stdio_nb_clients > 0)
2883 /***********************************************************/
2886 #define MAX_IO_HANDLERS 64
2888 typedef struct IOHandlerRecord {
2890 IOCanRWHandler *fd_read_poll;
2892 IOHandler *fd_write;
2894 /* temporary data */
2896 struct IOHandlerRecord *next;
2899 static IOHandlerRecord *first_io_handler;
2901 /* XXX: fd_read_poll should be suppressed, but an API change is
2902 necessary in the character devices to suppress fd_can_read(). */
2903 int qemu_set_fd_handler2(int fd,
2904 IOCanRWHandler *fd_read_poll,
2906 IOHandler *fd_write,
2909 IOHandlerRecord **pioh, *ioh;
2911 if (!fd_read && !fd_write) {
2912 pioh = &first_io_handler;
2917 if (ioh->fd == fd) {
2924 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2928 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
2931 ioh->next = first_io_handler;
2932 first_io_handler = ioh;
2935 ioh->fd_read_poll = fd_read_poll;
2936 ioh->fd_read = fd_read;
2937 ioh->fd_write = fd_write;
2938 ioh->opaque = opaque;
2943 int qemu_set_fd_handler(int fd,
2945 IOHandler *fd_write,
2948 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
2951 /***********************************************************/
2952 /* savevm/loadvm support */
2954 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
2956 fwrite(buf, 1, size, f);
2959 void qemu_put_byte(QEMUFile *f, int v)
2964 void qemu_put_be16(QEMUFile *f, unsigned int v)
2966 qemu_put_byte(f, v >> 8);
2967 qemu_put_byte(f, v);
2970 void qemu_put_be32(QEMUFile *f, unsigned int v)
2972 qemu_put_byte(f, v >> 24);
2973 qemu_put_byte(f, v >> 16);
2974 qemu_put_byte(f, v >> 8);
2975 qemu_put_byte(f, v);
2978 void qemu_put_be64(QEMUFile *f, uint64_t v)
2980 qemu_put_be32(f, v >> 32);
2981 qemu_put_be32(f, v);
2984 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size)
2986 return fread(buf, 1, size, f);
2989 int qemu_get_byte(QEMUFile *f)
2999 unsigned int qemu_get_be16(QEMUFile *f)
3002 v = qemu_get_byte(f) << 8;
3003 v |= qemu_get_byte(f);
3007 unsigned int qemu_get_be32(QEMUFile *f)
3010 v = qemu_get_byte(f) << 24;
3011 v |= qemu_get_byte(f) << 16;
3012 v |= qemu_get_byte(f) << 8;
3013 v |= qemu_get_byte(f);
3017 uint64_t qemu_get_be64(QEMUFile *f)
3020 v = (uint64_t)qemu_get_be32(f) << 32;
3021 v |= qemu_get_be32(f);
3025 int64_t qemu_ftell(QEMUFile *f)
3030 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
3032 if (fseek(f, pos, whence) < 0)
3037 typedef struct SaveStateEntry {
3041 SaveStateHandler *save_state;
3042 LoadStateHandler *load_state;
3044 struct SaveStateEntry *next;
3047 static SaveStateEntry *first_se;
3049 int register_savevm(const char *idstr,
3052 SaveStateHandler *save_state,
3053 LoadStateHandler *load_state,
3056 SaveStateEntry *se, **pse;
3058 se = qemu_malloc(sizeof(SaveStateEntry));
3061 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
3062 se->instance_id = instance_id;
3063 se->version_id = version_id;
3064 se->save_state = save_state;
3065 se->load_state = load_state;
3066 se->opaque = opaque;
3069 /* add at the end of list */
3071 while (*pse != NULL)
3072 pse = &(*pse)->next;
3077 #define QEMU_VM_FILE_MAGIC 0x5145564d
3078 #define QEMU_VM_FILE_VERSION 0x00000001
3080 int qemu_savevm(const char *filename)
3084 int len, len_pos, cur_pos, saved_vm_running, ret;
3086 saved_vm_running = vm_running;
3089 f = fopen(filename, "wb");
3095 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
3096 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
3098 for(se = first_se; se != NULL; se = se->next) {
3100 len = strlen(se->idstr);
3101 qemu_put_byte(f, len);
3102 qemu_put_buffer(f, se->idstr, len);
3104 qemu_put_be32(f, se->instance_id);
3105 qemu_put_be32(f, se->version_id);
3107 /* record size: filled later */
3109 qemu_put_be32(f, 0);
3111 se->save_state(f, se->opaque);
3113 /* fill record size */
3115 len = ftell(f) - len_pos - 4;
3116 fseek(f, len_pos, SEEK_SET);
3117 qemu_put_be32(f, len);
3118 fseek(f, cur_pos, SEEK_SET);
3124 if (saved_vm_running)
3129 static SaveStateEntry *find_se(const char *idstr, int instance_id)
3133 for(se = first_se; se != NULL; se = se->next) {
3134 if (!strcmp(se->idstr, idstr) &&
3135 instance_id == se->instance_id)
3141 int qemu_loadvm(const char *filename)
3145 int len, cur_pos, ret, instance_id, record_len, version_id;
3146 int saved_vm_running;
3150 saved_vm_running = vm_running;
3153 f = fopen(filename, "rb");
3159 v = qemu_get_be32(f);
3160 if (v != QEMU_VM_FILE_MAGIC)
3162 v = qemu_get_be32(f);
3163 if (v != QEMU_VM_FILE_VERSION) {
3170 len = qemu_get_byte(f);
3173 qemu_get_buffer(f, idstr, len);
3175 instance_id = qemu_get_be32(f);
3176 version_id = qemu_get_be32(f);
3177 record_len = qemu_get_be32(f);
3179 printf("idstr=%s instance=0x%x version=%d len=%d\n",
3180 idstr, instance_id, version_id, record_len);
3183 se = find_se(idstr, instance_id);
3185 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
3186 instance_id, idstr);
3188 ret = se->load_state(f, se->opaque, version_id);
3190 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
3191 instance_id, idstr);
3194 /* always seek to exact end of record */
3195 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
3200 if (saved_vm_running)
3205 /***********************************************************/
3206 /* cpu save/restore */
3208 #if defined(TARGET_I386)
3210 static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
3212 qemu_put_be32(f, dt->selector);
3213 qemu_put_betl(f, dt->base);
3214 qemu_put_be32(f, dt->limit);
3215 qemu_put_be32(f, dt->flags);
3218 static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
3220 dt->selector = qemu_get_be32(f);
3221 dt->base = qemu_get_betl(f);
3222 dt->limit = qemu_get_be32(f);
3223 dt->flags = qemu_get_be32(f);
3226 void cpu_save(QEMUFile *f, void *opaque)
3228 CPUState *env = opaque;
3229 uint16_t fptag, fpus, fpuc, fpregs_format;
3233 for(i = 0; i < CPU_NB_REGS; i++)
3234 qemu_put_betls(f, &env->regs[i]);
3235 qemu_put_betls(f, &env->eip);
3236 qemu_put_betls(f, &env->eflags);
3237 hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
3238 qemu_put_be32s(f, &hflags);
3242 fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
3244 for(i = 0; i < 8; i++) {
3245 fptag |= ((!env->fptags[i]) << i);
3248 qemu_put_be16s(f, &fpuc);
3249 qemu_put_be16s(f, &fpus);
3250 qemu_put_be16s(f, &fptag);
3252 #ifdef USE_X86LDOUBLE
3257 qemu_put_be16s(f, &fpregs_format);
3259 for(i = 0; i < 8; i++) {
3260 #ifdef USE_X86LDOUBLE
3264 /* we save the real CPU data (in case of MMX usage only 'mant'
3265 contains the MMX register */
3266 cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
3267 qemu_put_be64(f, mant);
3268 qemu_put_be16(f, exp);
3271 /* if we use doubles for float emulation, we save the doubles to
3272 avoid losing information in case of MMX usage. It can give
3273 problems if the image is restored on a CPU where long
3274 doubles are used instead. */
3275 qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
3279 for(i = 0; i < 6; i++)
3280 cpu_put_seg(f, &env->segs[i]);
3281 cpu_put_seg(f, &env->ldt);
3282 cpu_put_seg(f, &env->tr);
3283 cpu_put_seg(f, &env->gdt);
3284 cpu_put_seg(f, &env->idt);
3286 qemu_put_be32s(f, &env->sysenter_cs);
3287 qemu_put_be32s(f, &env->sysenter_esp);
3288 qemu_put_be32s(f, &env->sysenter_eip);
3290 qemu_put_betls(f, &env->cr[0]);
3291 qemu_put_betls(f, &env->cr[2]);
3292 qemu_put_betls(f, &env->cr[3]);
3293 qemu_put_betls(f, &env->cr[4]);
3295 for(i = 0; i < 8; i++)
3296 qemu_put_betls(f, &env->dr[i]);
3299 qemu_put_be32s(f, &env->a20_mask);
3302 qemu_put_be32s(f, &env->mxcsr);
3303 for(i = 0; i < CPU_NB_REGS; i++) {
3304 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
3305 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
3308 #ifdef TARGET_X86_64
3309 qemu_put_be64s(f, &env->efer);
3310 qemu_put_be64s(f, &env->star);
3311 qemu_put_be64s(f, &env->lstar);
3312 qemu_put_be64s(f, &env->cstar);
3313 qemu_put_be64s(f, &env->fmask);
3314 qemu_put_be64s(f, &env->kernelgsbase);
3318 #ifdef USE_X86LDOUBLE
3319 /* XXX: add that in a FPU generic layer */
3320 union x86_longdouble {
3325 #define MANTD1(fp) (fp & ((1LL << 52) - 1))
3326 #define EXPBIAS1 1023
3327 #define EXPD1(fp) ((fp >> 52) & 0x7FF)
3328 #define SIGND1(fp) ((fp >> 32) & 0x80000000)
3330 static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
3334 p->mant = (MANTD1(temp) << 11) | (1LL << 63);
3335 /* exponent + sign */
3336 e = EXPD1(temp) - EXPBIAS1 + 16383;
3337 e |= SIGND1(temp) >> 16;
3342 int cpu_load(QEMUFile *f, void *opaque, int version_id)
3344 CPUState *env = opaque;
3347 uint16_t fpus, fpuc, fptag, fpregs_format;
3349 if (version_id != 3)
3351 for(i = 0; i < CPU_NB_REGS; i++)
3352 qemu_get_betls(f, &env->regs[i]);
3353 qemu_get_betls(f, &env->eip);
3354 qemu_get_betls(f, &env->eflags);
3355 qemu_get_be32s(f, &hflags);
3357 qemu_get_be16s(f, &fpuc);
3358 qemu_get_be16s(f, &fpus);
3359 qemu_get_be16s(f, &fptag);
3360 qemu_get_be16s(f, &fpregs_format);
3362 /* NOTE: we cannot always restore the FPU state if the image come
3363 from a host with a different 'USE_X86LDOUBLE' define. We guess
3364 if we are in an MMX state to restore correctly in that case. */
3365 guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
3366 for(i = 0; i < 8; i++) {
3370 switch(fpregs_format) {
3372 mant = qemu_get_be64(f);
3373 exp = qemu_get_be16(f);
3374 #ifdef USE_X86LDOUBLE
3375 env->fpregs[i].d = cpu_set_fp80(mant, exp);
3377 /* difficult case */
3379 env->fpregs[i].mmx.MMX_Q(0) = mant;
3381 env->fpregs[i].d = cpu_set_fp80(mant, exp);
3385 mant = qemu_get_be64(f);
3386 #ifdef USE_X86LDOUBLE
3388 union x86_longdouble *p;
3389 /* difficult case */
3390 p = (void *)&env->fpregs[i];
3395 fp64_to_fp80(p, mant);
3399 env->fpregs[i].mmx.MMX_Q(0) = mant;
3408 /* XXX: restore FPU round state */
3409 env->fpstt = (fpus >> 11) & 7;
3410 env->fpus = fpus & ~0x3800;
3412 for(i = 0; i < 8; i++) {
3413 env->fptags[i] = (fptag >> i) & 1;
3416 for(i = 0; i < 6; i++)
3417 cpu_get_seg(f, &env->segs[i]);
3418 cpu_get_seg(f, &env->ldt);
3419 cpu_get_seg(f, &env->tr);
3420 cpu_get_seg(f, &env->gdt);
3421 cpu_get_seg(f, &env->idt);
3423 qemu_get_be32s(f, &env->sysenter_cs);
3424 qemu_get_be32s(f, &env->sysenter_esp);
3425 qemu_get_be32s(f, &env->sysenter_eip);
3427 qemu_get_betls(f, &env->cr[0]);
3428 qemu_get_betls(f, &env->cr[2]);
3429 qemu_get_betls(f, &env->cr[3]);
3430 qemu_get_betls(f, &env->cr[4]);
3432 for(i = 0; i < 8; i++)
3433 qemu_get_betls(f, &env->dr[i]);
3436 qemu_get_be32s(f, &env->a20_mask);
3438 qemu_get_be32s(f, &env->mxcsr);
3439 for(i = 0; i < CPU_NB_REGS; i++) {
3440 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
3441 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
3444 #ifdef TARGET_X86_64
3445 qemu_get_be64s(f, &env->efer);
3446 qemu_get_be64s(f, &env->star);
3447 qemu_get_be64s(f, &env->lstar);
3448 qemu_get_be64s(f, &env->cstar);
3449 qemu_get_be64s(f, &env->fmask);
3450 qemu_get_be64s(f, &env->kernelgsbase);
3453 /* XXX: compute hflags from scratch, except for CPL and IIF */
3454 env->hflags = hflags;
3459 #elif defined(TARGET_PPC)
3460 void cpu_save(QEMUFile *f, void *opaque)
3464 int cpu_load(QEMUFile *f, void *opaque, int version_id)
3469 #elif defined(TARGET_MIPS)
3470 void cpu_save(QEMUFile *f, void *opaque)
3474 int cpu_load(QEMUFile *f, void *opaque, int version_id)
3479 #elif defined(TARGET_SPARC)
3480 void cpu_save(QEMUFile *f, void *opaque)
3482 CPUState *env = opaque;
3486 for(i = 0; i < 8; i++)
3487 qemu_put_betls(f, &env->gregs[i]);
3488 for(i = 0; i < NWINDOWS * 16; i++)
3489 qemu_put_betls(f, &env->regbase[i]);
3492 for(i = 0; i < TARGET_FPREGS; i++) {
3498 qemu_put_betl(f, u.i);
3501 qemu_put_betls(f, &env->pc);
3502 qemu_put_betls(f, &env->npc);
3503 qemu_put_betls(f, &env->y);
3505 qemu_put_be32(f, tmp);
3506 qemu_put_betls(f, &env->fsr);
3507 qemu_put_betls(f, &env->tbr);
3508 #ifndef TARGET_SPARC64
3509 qemu_put_be32s(f, &env->wim);
3511 for(i = 0; i < 16; i++)
3512 qemu_put_be32s(f, &env->mmuregs[i]);
3516 int cpu_load(QEMUFile *f, void *opaque, int version_id)
3518 CPUState *env = opaque;
3522 for(i = 0; i < 8; i++)
3523 qemu_get_betls(f, &env->gregs[i]);
3524 for(i = 0; i < NWINDOWS * 16; i++)
3525 qemu_get_betls(f, &env->regbase[i]);
3528 for(i = 0; i < TARGET_FPREGS; i++) {
3533 u.i = qemu_get_betl(f);
3537 qemu_get_betls(f, &env->pc);
3538 qemu_get_betls(f, &env->npc);
3539 qemu_get_betls(f, &env->y);
3540 tmp = qemu_get_be32(f);
3541 env->cwp = 0; /* needed to ensure that the wrapping registers are
3542 correctly updated */
3544 qemu_get_betls(f, &env->fsr);
3545 qemu_get_betls(f, &env->tbr);
3546 #ifndef TARGET_SPARC64
3547 qemu_get_be32s(f, &env->wim);
3549 for(i = 0; i < 16; i++)
3550 qemu_get_be32s(f, &env->mmuregs[i]);
3556 #elif defined(TARGET_ARM)
3558 /* ??? Need to implement these. */
3559 void cpu_save(QEMUFile *f, void *opaque)
3563 int cpu_load(QEMUFile *f, void *opaque, int version_id)
3570 #warning No CPU save/restore functions
3574 /***********************************************************/
3575 /* ram save/restore */
3577 /* we just avoid storing empty pages */
3578 static void ram_put_page(QEMUFile *f, const uint8_t *buf, int len)
3583 for(i = 1; i < len; i++) {
3587 qemu_put_byte(f, 1);
3588 qemu_put_byte(f, v);
3591 qemu_put_byte(f, 0);
3592 qemu_put_buffer(f, buf, len);
3595 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
3599 v = qemu_get_byte(f);
3602 if (qemu_get_buffer(f, buf, len) != len)
3606 v = qemu_get_byte(f);
3607 memset(buf, v, len);
3615 static void ram_save(QEMUFile *f, void *opaque)
3618 qemu_put_be32(f, phys_ram_size);
3619 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
3620 ram_put_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
3624 static int ram_load(QEMUFile *f, void *opaque, int version_id)
3628 if (version_id != 1)
3630 if (qemu_get_be32(f) != phys_ram_size)
3632 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
3633 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
3640 /***********************************************************/
3641 /* machine registration */
3643 QEMUMachine *first_machine = NULL;
3645 int qemu_register_machine(QEMUMachine *m)
3648 pm = &first_machine;
3656 QEMUMachine *find_machine(const char *name)
3660 for(m = first_machine; m != NULL; m = m->next) {
3661 if (!strcmp(m->name, name))
3667 /***********************************************************/
3668 /* main execution loop */
3670 void gui_update(void *opaque)
3672 display_state.dpy_refresh(&display_state);
3673 qemu_mod_timer(gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
3676 struct vm_change_state_entry {
3677 VMChangeStateHandler *cb;
3679 LIST_ENTRY (vm_change_state_entry) entries;
3682 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3684 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3687 VMChangeStateEntry *e;
3689 e = qemu_mallocz(sizeof (*e));
3695 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3699 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3701 LIST_REMOVE (e, entries);
3705 static void vm_state_notify(int running)
3707 VMChangeStateEntry *e;
3709 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3710 e->cb(e->opaque, running);
3714 /* XXX: support several handlers */
3715 static VMStopHandler *vm_stop_cb;
3716 static void *vm_stop_opaque;
3718 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
3721 vm_stop_opaque = opaque;
3725 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
3739 void vm_stop(int reason)
3742 cpu_disable_ticks();
3746 vm_stop_cb(vm_stop_opaque, reason);
3753 /* reset/shutdown handler */
3755 typedef struct QEMUResetEntry {
3756 QEMUResetHandler *func;
3758 struct QEMUResetEntry *next;
3761 static QEMUResetEntry *first_reset_entry;
3762 static int reset_requested;
3763 static int shutdown_requested;
3764 static int powerdown_requested;
3766 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
3768 QEMUResetEntry **pre, *re;
3770 pre = &first_reset_entry;
3771 while (*pre != NULL)
3772 pre = &(*pre)->next;
3773 re = qemu_mallocz(sizeof(QEMUResetEntry));
3775 re->opaque = opaque;
3780 void qemu_system_reset(void)
3784 /* reset all devices */
3785 for(re = first_reset_entry; re != NULL; re = re->next) {
3786 re->func(re->opaque);
3790 void qemu_system_reset_request(void)
3792 reset_requested = 1;
3794 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
3797 void qemu_system_shutdown_request(void)
3799 shutdown_requested = 1;
3801 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
3804 void qemu_system_powerdown_request(void)
3806 powerdown_requested = 1;
3808 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
3811 void main_loop_wait(int timeout)
3814 struct pollfd ufds[MAX_IO_HANDLERS + 1], *pf;
3815 IOHandlerRecord *ioh, *ioh_next;
3823 /* poll any events */
3824 /* XXX: separate device handlers from system ones */
3826 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3830 (!ioh->fd_read_poll ||
3831 ioh->fd_read_poll(ioh->opaque) != 0)) {
3832 pf->events |= POLLIN;
3834 if (ioh->fd_write) {
3835 pf->events |= POLLOUT;
3841 ret = poll(ufds, pf - ufds, timeout);
3843 /* XXX: better handling of removal */
3844 for(ioh = first_io_handler; ioh != NULL; ioh = ioh_next) {
3845 ioh_next = ioh->next;
3847 if (pf->revents & POLLIN) {
3848 ioh->fd_read(ioh->opaque);
3850 if (pf->revents & POLLOUT) {
3851 ioh->fd_write(ioh->opaque);
3855 #endif /* !defined(_WIN32) */
3856 #if defined(CONFIG_SLIRP)
3857 /* XXX: merge with poll() */
3859 fd_set rfds, wfds, xfds;
3867 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
3870 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
3872 slirp_select_poll(&rfds, &wfds, &xfds);
3878 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
3879 qemu_get_clock(vm_clock));
3880 /* run dma transfers, if any */
3884 /* real time timers */
3885 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
3886 qemu_get_clock(rt_clock));
3889 static CPUState *cur_cpu;
3896 cur_cpu = first_cpu;
3903 env = env->next_cpu;
3906 ret = cpu_exec(env);
3907 if (ret != EXCP_HALTED)
3909 /* all CPUs are halted ? */
3910 if (env == cur_cpu) {
3917 if (shutdown_requested) {
3918 ret = EXCP_INTERRUPT;
3921 if (reset_requested) {
3922 reset_requested = 0;
3923 qemu_system_reset();
3924 ret = EXCP_INTERRUPT;
3926 if (powerdown_requested) {
3927 powerdown_requested = 0;
3928 qemu_system_powerdown();
3929 ret = EXCP_INTERRUPT;
3931 if (ret == EXCP_DEBUG) {
3932 vm_stop(EXCP_DEBUG);
3934 /* if hlt instruction, we wait until the next IRQ */
3935 /* XXX: use timeout computed from timers */
3936 if (ret == EXCP_HLT)
3943 main_loop_wait(timeout);
3945 cpu_disable_ticks();
3951 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2005 Fabrice Bellard\n"
3952 "usage: %s [options] [disk_image]\n"
3954 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
3956 "Standard options:\n"
3957 "-M machine select emulated machine (-M ? for list)\n"
3958 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
3959 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
3960 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
3961 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
3962 "-boot [a|c|d] boot on floppy (a), hard disk (c) or CD-ROM (d)\n"
3963 "-snapshot write to temporary files instead of disk image files\n"
3964 "-m megs set virtual RAM size to megs MB [default=%d]\n"
3965 "-nographic disable graphical output and redirect serial I/Os to console\n"
3967 "-k language use keyboard layout (for example \"fr\" for French)\n"
3970 "-enable-audio enable audio support, and all the sound cars\n"
3971 "-audio-help print list of audio drivers and their options\n"
3972 "-soundhw c1,... enable audio support\n"
3973 " and only specified sound cards (comma separated list)\n"
3974 " use -soundhw ? to get the list of supported cards\n"
3976 "-localtime set the real time clock to local time [default=utc]\n"
3977 "-full-screen start in full screen\n"
3979 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
3981 "-usb enable the USB driver (will be the default soon)\n"
3982 "-usbdevice name add the host or guest USB device 'name'\n"
3983 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
3984 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
3987 "Network options:\n"
3988 "-net nic[,vlan=n][,macaddr=addr]\n"
3989 " create a new Network Interface Card and connect it to VLAN 'n'\n"
3991 "-net user[,vlan=n]\n"
3992 " connect the user mode network stack to VLAN 'n'\n"
3995 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file]\n"
3996 " connect the host TAP network interface to VLAN 'n' and use\n"
3997 " the network script 'file' (default=%s);\n"
3998 " use 'fd=h' to connect to an already opened TAP interface\n"
3999 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
4000 " connect the vlan 'n' to another VLAN using a socket connection\n"
4001 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
4002 " connect the vlan 'n' to multicast maddr and port\n"
4004 "-net none use it alone to have zero network devices; if no -net option\n"
4005 " is provided, the default is '-net nic -net user'\n"
4008 "-tftp prefix allow tftp access to files starting with prefix [-net user]\n"
4010 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
4012 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
4013 " redirect TCP or UDP connections from host to guest [-net user]\n"
4016 "Linux boot specific:\n"
4017 "-kernel bzImage use 'bzImage' as kernel image\n"
4018 "-append cmdline use 'cmdline' as kernel command line\n"
4019 "-initrd file use 'file' as initial ram disk\n"
4021 "Debug/Expert options:\n"
4022 "-monitor dev redirect the monitor to char device 'dev'\n"
4023 "-serial dev redirect the serial port to char device 'dev'\n"
4024 "-parallel dev redirect the parallel port to char device 'dev'\n"
4025 "-pidfile file Write PID to 'file'\n"
4026 "-S freeze CPU at startup (use 'c' to start execution)\n"
4027 "-s wait gdb connection to port %d\n"
4028 "-p port change gdb connection port\n"
4029 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
4030 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
4031 " translation (t=none or lba) (usually qemu can guess them)\n"
4032 "-L path set the directory for the BIOS and VGA BIOS\n"
4034 "-no-kqemu disable KQEMU kernel module usage\n"
4036 #ifdef USE_CODE_COPY
4037 "-no-code-copy disable code copy acceleration\n"
4040 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
4041 " (default is CL-GD5446 PCI VGA)\n"
4043 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
4045 "During emulation, the following keys are useful:\n"
4046 "ctrl-alt-f toggle full screen\n"
4047 "ctrl-alt-n switch to virtual console 'n'\n"
4048 "ctrl-alt toggle mouse and keyboard grab\n"
4050 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4052 #ifdef CONFIG_SOFTMMU
4059 DEFAULT_NETWORK_SCRIPT,
4061 DEFAULT_GDBSTUB_PORT,
4063 #ifndef CONFIG_SOFTMMU
4065 "NOTE: this version of QEMU is faster but it needs slightly patched OSes to\n"
4066 "work. Please use the 'qemu' executable to have a more accurate (but slower)\n"
4072 #define HAS_ARG 0x0001
4086 QEMU_OPTION_snapshot,
4088 QEMU_OPTION_nographic,
4090 QEMU_OPTION_enable_audio,
4091 QEMU_OPTION_audio_help,
4092 QEMU_OPTION_soundhw,
4110 QEMU_OPTION_no_code_copy,
4112 QEMU_OPTION_localtime,
4113 QEMU_OPTION_cirrusvga,
4115 QEMU_OPTION_std_vga,
4116 QEMU_OPTION_monitor,
4118 QEMU_OPTION_parallel,
4120 QEMU_OPTION_full_screen,
4121 QEMU_OPTION_pidfile,
4122 QEMU_OPTION_no_kqemu,
4123 QEMU_OPTION_win2k_hack,
4125 QEMU_OPTION_usbdevice,
4129 typedef struct QEMUOption {
4135 const QEMUOption qemu_options[] = {
4136 { "h", 0, QEMU_OPTION_h },
4138 { "M", HAS_ARG, QEMU_OPTION_M },
4139 { "fda", HAS_ARG, QEMU_OPTION_fda },
4140 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
4141 { "hda", HAS_ARG, QEMU_OPTION_hda },
4142 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
4143 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
4144 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
4145 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
4146 { "boot", HAS_ARG, QEMU_OPTION_boot },
4147 { "snapshot", 0, QEMU_OPTION_snapshot },
4148 { "m", HAS_ARG, QEMU_OPTION_m },
4149 { "nographic", 0, QEMU_OPTION_nographic },
4150 { "k", HAS_ARG, QEMU_OPTION_k },
4152 { "enable-audio", 0, QEMU_OPTION_enable_audio },
4153 { "audio-help", 0, QEMU_OPTION_audio_help },
4154 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
4157 { "net", HAS_ARG, QEMU_OPTION_net},
4159 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
4161 { "smb", HAS_ARG, QEMU_OPTION_smb },
4163 { "redir", HAS_ARG, QEMU_OPTION_redir },
4166 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
4167 { "append", HAS_ARG, QEMU_OPTION_append },
4168 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
4170 { "S", 0, QEMU_OPTION_S },
4171 { "s", 0, QEMU_OPTION_s },
4172 { "p", HAS_ARG, QEMU_OPTION_p },
4173 { "d", HAS_ARG, QEMU_OPTION_d },
4174 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
4175 { "L", HAS_ARG, QEMU_OPTION_L },
4176 { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
4178 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
4180 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
4181 { "g", 1, QEMU_OPTION_g },
4183 { "localtime", 0, QEMU_OPTION_localtime },
4184 { "std-vga", 0, QEMU_OPTION_std_vga },
4185 { "monitor", 1, QEMU_OPTION_monitor },
4186 { "serial", 1, QEMU_OPTION_serial },
4187 { "parallel", 1, QEMU_OPTION_parallel },
4188 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
4189 { "full-screen", 0, QEMU_OPTION_full_screen },
4190 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
4191 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
4192 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
4193 { "smp", HAS_ARG, QEMU_OPTION_smp },
4195 /* temporary options */
4196 { "usb", 0, QEMU_OPTION_usb },
4197 { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
4201 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
4203 /* this stack is only used during signal handling */
4204 #define SIGNAL_STACK_SIZE 32768
4206 static uint8_t *signal_stack;
4210 /* password input */
4212 static BlockDriverState *get_bdrv(int index)
4214 BlockDriverState *bs;
4217 bs = bs_table[index];
4218 } else if (index < 6) {
4219 bs = fd_table[index - 4];
4226 static void read_passwords(void)
4228 BlockDriverState *bs;
4232 for(i = 0; i < 6; i++) {
4234 if (bs && bdrv_is_encrypted(bs)) {
4235 term_printf("%s is encrypted.\n", bdrv_get_device_name(bs));
4236 for(j = 0; j < 3; j++) {
4237 monitor_readline("Password: ",
4238 1, password, sizeof(password));
4239 if (bdrv_set_key(bs, password) == 0)
4241 term_printf("invalid password\n");
4247 /* XXX: currently we cannot use simultaneously different CPUs */
4248 void register_machines(void)
4250 #if defined(TARGET_I386)
4251 qemu_register_machine(&pc_machine);
4252 qemu_register_machine(&isapc_machine);
4253 #elif defined(TARGET_PPC)
4254 qemu_register_machine(&heathrow_machine);
4255 qemu_register_machine(&core99_machine);
4256 qemu_register_machine(&prep_machine);
4257 #elif defined(TARGET_MIPS)
4258 qemu_register_machine(&mips_machine);
4259 #elif defined(TARGET_SPARC)
4260 #ifdef TARGET_SPARC64
4261 qemu_register_machine(&sun4u_machine);
4263 qemu_register_machine(&sun4m_machine);
4265 #elif defined(TARGET_ARM)
4266 qemu_register_machine(&integratorcp_machine);
4268 #error unsupported CPU
4273 static void select_soundhw (const char *optarg)
4275 if (*optarg == '?') {
4277 printf ("Valid sound card names (comma separated):\n");
4278 printf ("sb16 Creative Sound Blaster 16\n");
4281 printf ("adlib Yamaha YMF262 (OPL3)\n");
4283 printf ("adlib Yamaha YM3812 (OPL2)\n");
4287 printf ("gus Gravis Ultrasound GF1\n");
4289 printf ("es1370 ENSONIQ AudioPCI ES1370\n");
4290 exit (*optarg != '?');
4297 { "sb16", &sb16_enabled },
4299 { "adlib", &adlib_enabled },
4302 { "gus", &gus_enabled },
4304 { "es1370", &es1370_enabled },
4306 size_t tablen, l, i;
4312 tablen = sizeof (soundhw_tab) / sizeof (soundhw_tab[0]);
4315 e = strchr (p, ',');
4316 l = !e ? strlen (p) : (size_t) (e - p);
4317 for (i = 0; i < tablen; ++i) {
4318 if (!strncmp (soundhw_tab[i].name, p, l)) {
4320 *soundhw_tab[i].enabledp = 1;
4327 "Unknown sound card name (too big to show)\n");
4330 fprintf (stderr, "Unknown sound card name `%.*s'\n",
4335 p += l + (e != NULL);
4339 goto show_valid_cards;
4344 #define MAX_NET_CLIENTS 32
4346 int main(int argc, char **argv)
4348 #ifdef CONFIG_GDBSTUB
4349 int use_gdbstub, gdbstub_port;
4352 int snapshot, linux_boot;
4353 const char *initrd_filename;
4354 const char *hd_filename[MAX_DISKS], *fd_filename[MAX_FD];
4355 const char *kernel_filename, *kernel_cmdline;
4356 DisplayState *ds = &display_state;
4357 int cyls, heads, secs, translation;
4358 int start_emulation = 1;
4359 char net_clients[MAX_NET_CLIENTS][256];
4362 const char *r, *optarg;
4363 CharDriverState *monitor_hd;
4364 char monitor_device[128];
4365 char serial_devices[MAX_SERIAL_PORTS][128];
4366 int serial_device_index;
4367 char parallel_devices[MAX_PARALLEL_PORTS][128];
4368 int parallel_device_index;
4369 const char *loadvm = NULL;
4370 QEMUMachine *machine;
4371 char usb_devices[MAX_VM_USB_PORTS][128];
4372 int usb_devices_index;
4374 LIST_INIT (&vm_change_state_head);
4375 #if !defined(CONFIG_SOFTMMU)
4376 /* we never want that malloc() uses mmap() */
4377 mallopt(M_MMAP_THRESHOLD, 4096 * 1024);
4379 register_machines();
4380 machine = first_machine;
4381 initrd_filename = NULL;
4382 for(i = 0; i < MAX_FD; i++)
4383 fd_filename[i] = NULL;
4384 for(i = 0; i < MAX_DISKS; i++)
4385 hd_filename[i] = NULL;
4386 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
4387 vga_ram_size = VGA_RAM_SIZE;
4388 bios_size = BIOS_SIZE;
4389 #ifdef CONFIG_GDBSTUB
4391 gdbstub_port = DEFAULT_GDBSTUB_PORT;
4395 kernel_filename = NULL;
4396 kernel_cmdline = "";
4402 cyls = heads = secs = 0;
4403 translation = BIOS_ATA_TRANSLATION_AUTO;
4404 pstrcpy(monitor_device, sizeof(monitor_device), "vc");
4406 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
4407 for(i = 1; i < MAX_SERIAL_PORTS; i++)
4408 serial_devices[i][0] = '\0';
4409 serial_device_index = 0;
4411 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
4412 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
4413 parallel_devices[i][0] = '\0';
4414 parallel_device_index = 0;
4416 usb_devices_index = 0;
4421 /* default mac address of the first network interface */
4429 hd_filename[0] = argv[optind++];
4431 const QEMUOption *popt;
4434 popt = qemu_options;
4437 fprintf(stderr, "%s: invalid option -- '%s'\n",
4441 if (!strcmp(popt->name, r + 1))
4445 if (popt->flags & HAS_ARG) {
4446 if (optind >= argc) {
4447 fprintf(stderr, "%s: option '%s' requires an argument\n",
4451 optarg = argv[optind++];
4456 switch(popt->index) {
4458 machine = find_machine(optarg);
4461 printf("Supported machines are:\n");
4462 for(m = first_machine; m != NULL; m = m->next) {
4463 printf("%-10s %s%s\n",
4465 m == first_machine ? " (default)" : "");
4470 case QEMU_OPTION_initrd:
4471 initrd_filename = optarg;
4473 case QEMU_OPTION_hda:
4474 case QEMU_OPTION_hdb:
4475 case QEMU_OPTION_hdc:
4476 case QEMU_OPTION_hdd:
4479 hd_index = popt->index - QEMU_OPTION_hda;
4480 hd_filename[hd_index] = optarg;
4481 if (hd_index == cdrom_index)
4485 case QEMU_OPTION_snapshot:
4488 case QEMU_OPTION_hdachs:
4492 cyls = strtol(p, (char **)&p, 0);
4493 if (cyls < 1 || cyls > 16383)
4498 heads = strtol(p, (char **)&p, 0);
4499 if (heads < 1 || heads > 16)
4504 secs = strtol(p, (char **)&p, 0);
4505 if (secs < 1 || secs > 63)
4509 if (!strcmp(p, "none"))
4510 translation = BIOS_ATA_TRANSLATION_NONE;
4511 else if (!strcmp(p, "lba"))
4512 translation = BIOS_ATA_TRANSLATION_LBA;
4513 else if (!strcmp(p, "auto"))
4514 translation = BIOS_ATA_TRANSLATION_AUTO;
4517 } else if (*p != '\0') {
4519 fprintf(stderr, "qemu: invalid physical CHS format\n");
4524 case QEMU_OPTION_nographic:
4525 pstrcpy(monitor_device, sizeof(monitor_device), "stdio");
4526 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "stdio");
4529 case QEMU_OPTION_kernel:
4530 kernel_filename = optarg;
4532 case QEMU_OPTION_append:
4533 kernel_cmdline = optarg;
4535 case QEMU_OPTION_cdrom:
4536 if (cdrom_index >= 0) {
4537 hd_filename[cdrom_index] = optarg;
4540 case QEMU_OPTION_boot:
4541 boot_device = optarg[0];
4542 if (boot_device != 'a' &&
4545 boot_device != 'n' &&
4547 boot_device != 'c' && boot_device != 'd') {
4548 fprintf(stderr, "qemu: invalid boot device '%c'\n", boot_device);
4552 case QEMU_OPTION_fda:
4553 fd_filename[0] = optarg;
4555 case QEMU_OPTION_fdb:
4556 fd_filename[1] = optarg;
4558 case QEMU_OPTION_no_code_copy:
4559 code_copy_enabled = 0;
4561 case QEMU_OPTION_net:
4562 if (nb_net_clients >= MAX_NET_CLIENTS) {
4563 fprintf(stderr, "qemu: too many network clients\n");
4566 pstrcpy(net_clients[nb_net_clients],
4567 sizeof(net_clients[0]),
4572 case QEMU_OPTION_tftp:
4573 tftp_prefix = optarg;
4576 case QEMU_OPTION_smb:
4577 net_slirp_smb(optarg);
4580 case QEMU_OPTION_redir:
4581 net_slirp_redir(optarg);
4585 case QEMU_OPTION_enable_audio:
4592 case QEMU_OPTION_audio_help:
4596 case QEMU_OPTION_soundhw:
4597 select_soundhw (optarg);
4604 ram_size = atoi(optarg) * 1024 * 1024;
4607 if (ram_size > PHYS_RAM_MAX_SIZE) {
4608 fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
4609 PHYS_RAM_MAX_SIZE / (1024 * 1024));
4618 mask = cpu_str_to_log_mask(optarg);
4620 printf("Log items (comma separated):\n");
4621 for(item = cpu_log_items; item->mask != 0; item++) {
4622 printf("%-10s %s\n", item->name, item->help);
4629 #ifdef CONFIG_GDBSTUB
4634 gdbstub_port = atoi(optarg);
4641 start_emulation = 0;
4644 keyboard_layout = optarg;
4646 case QEMU_OPTION_localtime:
4649 case QEMU_OPTION_cirrusvga:
4650 cirrus_vga_enabled = 1;
4652 case QEMU_OPTION_std_vga:
4653 cirrus_vga_enabled = 0;
4660 w = strtol(p, (char **)&p, 10);
4663 fprintf(stderr, "qemu: invalid resolution or depth\n");
4669 h = strtol(p, (char **)&p, 10);
4674 depth = strtol(p, (char **)&p, 10);
4675 if (depth != 8 && depth != 15 && depth != 16 &&
4676 depth != 24 && depth != 32)
4678 } else if (*p == '\0') {
4679 depth = graphic_depth;
4686 graphic_depth = depth;
4689 case QEMU_OPTION_monitor:
4690 pstrcpy(monitor_device, sizeof(monitor_device), optarg);
4692 case QEMU_OPTION_serial:
4693 if (serial_device_index >= MAX_SERIAL_PORTS) {
4694 fprintf(stderr, "qemu: too many serial ports\n");
4697 pstrcpy(serial_devices[serial_device_index],
4698 sizeof(serial_devices[0]), optarg);
4699 serial_device_index++;
4701 case QEMU_OPTION_parallel:
4702 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
4703 fprintf(stderr, "qemu: too many parallel ports\n");
4706 pstrcpy(parallel_devices[parallel_device_index],
4707 sizeof(parallel_devices[0]), optarg);
4708 parallel_device_index++;
4710 case QEMU_OPTION_loadvm:
4713 case QEMU_OPTION_full_screen:
4716 case QEMU_OPTION_pidfile:
4717 create_pidfile(optarg);
4720 case QEMU_OPTION_win2k_hack:
4721 win2k_install_hack = 1;
4725 case QEMU_OPTION_no_kqemu:
4729 case QEMU_OPTION_usb:
4732 case QEMU_OPTION_usbdevice:
4734 if (usb_devices_index >= MAX_VM_USB_PORTS) {
4735 fprintf(stderr, "Too many USB devices\n");
4738 pstrcpy(usb_devices[usb_devices_index],
4739 sizeof(usb_devices[usb_devices_index]),
4741 usb_devices_index++;
4743 case QEMU_OPTION_smp:
4744 smp_cpus = atoi(optarg);
4745 if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
4746 fprintf(stderr, "Invalid number of CPUs\n");
4754 linux_boot = (kernel_filename != NULL);
4757 hd_filename[0] == '\0' &&
4758 (cdrom_index >= 0 && hd_filename[cdrom_index] == '\0') &&
4759 fd_filename[0] == '\0')
4762 /* boot to cd by default if no hard disk */
4763 if (hd_filename[0] == '\0' && boot_device == 'c') {
4764 if (fd_filename[0] != '\0')
4770 #if !defined(CONFIG_SOFTMMU)
4771 /* must avoid mmap() usage of glibc by setting a buffer "by hand" */
4773 static uint8_t stdout_buf[4096];
4774 setvbuf(stdout, stdout_buf, _IOLBF, sizeof(stdout_buf));
4777 setvbuf(stdout, NULL, _IOLBF, 0);
4780 /* init network clients */
4781 if (nb_net_clients == 0) {
4782 /* if no clients, we use a default config */
4783 pstrcpy(net_clients[0], sizeof(net_clients[0]),
4785 pstrcpy(net_clients[1], sizeof(net_clients[0]),
4790 for(i = 0;i < nb_net_clients; i++) {
4791 if (net_client_init(net_clients[i]) < 0)
4795 /* init the memory */
4796 phys_ram_size = ram_size + vga_ram_size + bios_size;
4798 #ifdef CONFIG_SOFTMMU
4799 phys_ram_base = qemu_vmalloc(phys_ram_size);
4800 if (!phys_ram_base) {
4801 fprintf(stderr, "Could not allocate physical memory\n");
4805 /* as we must map the same page at several addresses, we must use
4810 tmpdir = getenv("QEMU_TMPDIR");
4813 snprintf(phys_ram_file, sizeof(phys_ram_file), "%s/vlXXXXXX", tmpdir);
4814 if (mkstemp(phys_ram_file) < 0) {
4815 fprintf(stderr, "Could not create temporary memory file '%s'\n",
4819 phys_ram_fd = open(phys_ram_file, O_CREAT | O_TRUNC | O_RDWR, 0600);
4820 if (phys_ram_fd < 0) {
4821 fprintf(stderr, "Could not open temporary memory file '%s'\n",
4825 ftruncate(phys_ram_fd, phys_ram_size);
4826 unlink(phys_ram_file);
4827 phys_ram_base = mmap(get_mmap_addr(phys_ram_size),
4829 PROT_WRITE | PROT_READ, MAP_SHARED | MAP_FIXED,
4831 if (phys_ram_base == MAP_FAILED) {
4832 fprintf(stderr, "Could not map physical memory\n");
4838 /* we always create the cdrom drive, even if no disk is there */
4840 if (cdrom_index >= 0) {
4841 bs_table[cdrom_index] = bdrv_new("cdrom");
4842 bdrv_set_type_hint(bs_table[cdrom_index], BDRV_TYPE_CDROM);
4845 /* open the virtual block devices */
4846 for(i = 0; i < MAX_DISKS; i++) {
4847 if (hd_filename[i]) {
4850 snprintf(buf, sizeof(buf), "hd%c", i + 'a');
4851 bs_table[i] = bdrv_new(buf);
4853 if (bdrv_open(bs_table[i], hd_filename[i], snapshot) < 0) {
4854 fprintf(stderr, "qemu: could not open hard disk image '%s'\n",
4858 if (i == 0 && cyls != 0) {
4859 bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
4860 bdrv_set_translation_hint(bs_table[i], translation);
4865 /* we always create at least one floppy disk */
4866 fd_table[0] = bdrv_new("fda");
4867 bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
4869 for(i = 0; i < MAX_FD; i++) {
4870 if (fd_filename[i]) {
4873 snprintf(buf, sizeof(buf), "fd%c", i + 'a');
4874 fd_table[i] = bdrv_new(buf);
4875 bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
4877 if (fd_filename[i] != '\0') {
4878 if (bdrv_open(fd_table[i], fd_filename[i], snapshot) < 0) {
4879 fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
4887 /* init USB devices */
4889 vm_usb_hub = usb_hub_init(vm_usb_ports, MAX_VM_USB_PORTS);
4890 for(i = 0; i < usb_devices_index; i++) {
4891 if (usb_device_add(usb_devices[i]) < 0) {
4892 fprintf(stderr, "Warning: could not add USB device %s\n",
4898 register_savevm("timer", 0, 1, timer_save, timer_load, NULL);
4899 register_savevm("ram", 0, 1, ram_save, ram_load, NULL);
4902 cpu_calibrate_ticks();
4906 dumb_display_init(ds);
4908 #if defined(CONFIG_SDL)
4909 sdl_display_init(ds, full_screen);
4910 #elif defined(CONFIG_COCOA)
4911 cocoa_display_init(ds, full_screen);
4913 dumb_display_init(ds);
4917 vga_console = graphic_console_init(ds);
4919 monitor_hd = qemu_chr_open(monitor_device);
4921 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
4924 monitor_init(monitor_hd, !nographic);
4926 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
4927 if (serial_devices[i][0] != '\0') {
4928 serial_hds[i] = qemu_chr_open(serial_devices[i]);
4929 if (!serial_hds[i]) {
4930 fprintf(stderr, "qemu: could not open serial device '%s'\n",
4934 if (!strcmp(serial_devices[i], "vc"))
4935 qemu_chr_printf(serial_hds[i], "serial%d console\n", i);
4939 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
4940 if (parallel_devices[i][0] != '\0') {
4941 parallel_hds[i] = qemu_chr_open(parallel_devices[i]);
4942 if (!parallel_hds[i]) {
4943 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
4944 parallel_devices[i]);
4947 if (!strcmp(parallel_devices[i], "vc"))
4948 qemu_chr_printf(parallel_hds[i], "parallel%d console\n", i);
4952 /* setup cpu signal handlers for MMU / self modifying code handling */
4953 #if !defined(CONFIG_SOFTMMU)
4955 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
4958 signal_stack = memalign(16, SIGNAL_STACK_SIZE);
4959 stk.ss_sp = signal_stack;
4960 stk.ss_size = SIGNAL_STACK_SIZE;
4963 if (sigaltstack(&stk, NULL) < 0) {
4964 perror("sigaltstack");
4970 struct sigaction act;
4972 sigfillset(&act.sa_mask);
4973 act.sa_flags = SA_SIGINFO;
4974 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
4975 act.sa_flags |= SA_ONSTACK;
4977 act.sa_sigaction = host_segv_handler;
4978 sigaction(SIGSEGV, &act, NULL);
4979 sigaction(SIGBUS, &act, NULL);
4980 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
4981 sigaction(SIGFPE, &act, NULL);
4988 struct sigaction act;
4989 sigfillset(&act.sa_mask);
4991 act.sa_handler = SIG_IGN;
4992 sigaction(SIGPIPE, &act, NULL);
4997 machine->init(ram_size, vga_ram_size, boot_device,
4998 ds, fd_filename, snapshot,
4999 kernel_filename, kernel_cmdline, initrd_filename);
5001 gui_timer = qemu_new_timer(rt_clock, gui_update, NULL);
5002 qemu_mod_timer(gui_timer, qemu_get_clock(rt_clock));
5004 #ifdef CONFIG_GDBSTUB
5006 if (gdbserver_start(gdbstub_port) < 0) {
5007 fprintf(stderr, "Could not open gdbserver socket on port %d\n",
5011 printf("Waiting gdb connection on port %d\n", gdbstub_port);
5016 qemu_loadvm(loadvm);
5019 /* XXX: simplify init */
5021 if (start_emulation) {