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>
69 #define getopt_long_only getopt_long
70 #define memalign(align, size) malloc(size)
77 #endif /* CONFIG_SDL */
81 #define main qemu_main
82 #endif /* CONFIG_COCOA */
88 #define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
90 //#define DEBUG_UNUSED_IOPORT
91 //#define DEBUG_IOPORT
93 #if !defined(CONFIG_SOFTMMU)
94 #define PHYS_RAM_MAX_SIZE (256 * 1024 * 1024)
96 #define PHYS_RAM_MAX_SIZE (2047 * 1024 * 1024)
100 #define DEFAULT_RAM_SIZE 144
102 #define DEFAULT_RAM_SIZE 128
105 #define GUI_REFRESH_INTERVAL 30
107 /* XXX: use a two level table to limit memory usage */
108 #define MAX_IOPORTS 65536
110 const char *bios_dir = CONFIG_QEMU_SHAREDIR;
111 char phys_ram_file[1024];
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 int pit_min_timer_count = 0;
126 NICInfo nd_table[MAX_NICS];
127 QEMUTimer *gui_timer;
130 int cirrus_vga_enabled = 1;
132 int graphic_width = 1024;
133 int graphic_height = 768;
135 int graphic_width = 800;
136 int graphic_height = 600;
138 int graphic_depth = 15;
140 TextConsole *vga_console;
141 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
142 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
144 int win2k_install_hack = 0;
147 USBPort *vm_usb_ports[MAX_VM_USB_PORTS];
148 USBDevice *vm_usb_hub;
149 static VLANState *first_vlan;
151 #if defined(TARGET_SPARC)
153 #elif defined(TARGET_I386)
159 /***********************************************************/
160 /* x86 ISA bus support */
162 target_phys_addr_t isa_mem_base = 0;
165 uint32_t default_ioport_readb(void *opaque, uint32_t address)
167 #ifdef DEBUG_UNUSED_IOPORT
168 fprintf(stderr, "inb: port=0x%04x\n", address);
173 void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
175 #ifdef DEBUG_UNUSED_IOPORT
176 fprintf(stderr, "outb: port=0x%04x data=0x%02x\n", address, data);
180 /* default is to make two byte accesses */
181 uint32_t default_ioport_readw(void *opaque, uint32_t address)
184 data = ioport_read_table[0][address](ioport_opaque[address], address);
185 address = (address + 1) & (MAX_IOPORTS - 1);
186 data |= ioport_read_table[0][address](ioport_opaque[address], address) << 8;
190 void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
192 ioport_write_table[0][address](ioport_opaque[address], address, data & 0xff);
193 address = (address + 1) & (MAX_IOPORTS - 1);
194 ioport_write_table[0][address](ioport_opaque[address], address, (data >> 8) & 0xff);
197 uint32_t default_ioport_readl(void *opaque, uint32_t address)
199 #ifdef DEBUG_UNUSED_IOPORT
200 fprintf(stderr, "inl: port=0x%04x\n", address);
205 void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
207 #ifdef DEBUG_UNUSED_IOPORT
208 fprintf(stderr, "outl: port=0x%04x data=0x%02x\n", address, data);
212 void init_ioports(void)
216 for(i = 0; i < MAX_IOPORTS; i++) {
217 ioport_read_table[0][i] = default_ioport_readb;
218 ioport_write_table[0][i] = default_ioport_writeb;
219 ioport_read_table[1][i] = default_ioport_readw;
220 ioport_write_table[1][i] = default_ioport_writew;
221 ioport_read_table[2][i] = default_ioport_readl;
222 ioport_write_table[2][i] = default_ioport_writel;
226 /* size is the word size in byte */
227 int register_ioport_read(int start, int length, int size,
228 IOPortReadFunc *func, void *opaque)
234 } else if (size == 2) {
236 } else if (size == 4) {
239 hw_error("register_ioport_read: invalid size");
242 for(i = start; i < start + length; i += size) {
243 ioport_read_table[bsize][i] = func;
244 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
245 hw_error("register_ioport_read: invalid opaque");
246 ioport_opaque[i] = opaque;
251 /* size is the word size in byte */
252 int register_ioport_write(int start, int length, int size,
253 IOPortWriteFunc *func, void *opaque)
259 } else if (size == 2) {
261 } else if (size == 4) {
264 hw_error("register_ioport_write: invalid size");
267 for(i = start; i < start + length; i += size) {
268 ioport_write_table[bsize][i] = func;
269 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
270 hw_error("register_ioport_read: invalid opaque");
271 ioport_opaque[i] = opaque;
276 void isa_unassign_ioport(int start, int length)
280 for(i = start; i < start + length; i++) {
281 ioport_read_table[0][i] = default_ioport_readb;
282 ioport_read_table[1][i] = default_ioport_readw;
283 ioport_read_table[2][i] = default_ioport_readl;
285 ioport_write_table[0][i] = default_ioport_writeb;
286 ioport_write_table[1][i] = default_ioport_writew;
287 ioport_write_table[2][i] = default_ioport_writel;
291 /***********************************************************/
293 void pstrcpy(char *buf, int buf_size, const char *str)
303 if (c == 0 || q >= buf + buf_size - 1)
310 /* strcat and truncate. */
311 char *pstrcat(char *buf, int buf_size, const char *s)
316 pstrcpy(buf + len, buf_size - len, s);
320 int strstart(const char *str, const char *val, const char **ptr)
336 /* return the size or -1 if error */
337 int get_image_size(const char *filename)
340 fd = open(filename, O_RDONLY | O_BINARY);
343 size = lseek(fd, 0, SEEK_END);
348 /* return the size or -1 if error */
349 int load_image(const char *filename, uint8_t *addr)
352 fd = open(filename, O_RDONLY | O_BINARY);
355 size = lseek(fd, 0, SEEK_END);
356 lseek(fd, 0, SEEK_SET);
357 if (read(fd, addr, size) != size) {
365 void cpu_outb(CPUState *env, int addr, int val)
368 if (loglevel & CPU_LOG_IOPORT)
369 fprintf(logfile, "outb: %04x %02x\n", addr, val);
371 ioport_write_table[0][addr](ioport_opaque[addr], addr, val);
374 env->last_io_time = cpu_get_time_fast();
378 void cpu_outw(CPUState *env, int addr, int val)
381 if (loglevel & CPU_LOG_IOPORT)
382 fprintf(logfile, "outw: %04x %04x\n", addr, val);
384 ioport_write_table[1][addr](ioport_opaque[addr], addr, val);
387 env->last_io_time = cpu_get_time_fast();
391 void cpu_outl(CPUState *env, int addr, int val)
394 if (loglevel & CPU_LOG_IOPORT)
395 fprintf(logfile, "outl: %04x %08x\n", addr, val);
397 ioport_write_table[2][addr](ioport_opaque[addr], addr, val);
400 env->last_io_time = cpu_get_time_fast();
404 int cpu_inb(CPUState *env, int addr)
407 val = ioport_read_table[0][addr](ioport_opaque[addr], addr);
409 if (loglevel & CPU_LOG_IOPORT)
410 fprintf(logfile, "inb : %04x %02x\n", addr, val);
414 env->last_io_time = cpu_get_time_fast();
419 int cpu_inw(CPUState *env, int addr)
422 val = ioport_read_table[1][addr](ioport_opaque[addr], addr);
424 if (loglevel & CPU_LOG_IOPORT)
425 fprintf(logfile, "inw : %04x %04x\n", addr, val);
429 env->last_io_time = cpu_get_time_fast();
434 int cpu_inl(CPUState *env, int addr)
437 val = ioport_read_table[2][addr](ioport_opaque[addr], addr);
439 if (loglevel & CPU_LOG_IOPORT)
440 fprintf(logfile, "inl : %04x %08x\n", addr, val);
444 env->last_io_time = cpu_get_time_fast();
449 /***********************************************************/
450 void hw_error(const char *fmt, ...)
456 fprintf(stderr, "qemu: hardware error: ");
457 vfprintf(stderr, fmt, ap);
458 fprintf(stderr, "\n");
459 for(env = first_cpu; env != NULL; env = env->next_cpu) {
460 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
462 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
464 cpu_dump_state(env, stderr, fprintf, 0);
471 /***********************************************************/
474 static QEMUPutKBDEvent *qemu_put_kbd_event;
475 static void *qemu_put_kbd_event_opaque;
476 static QEMUPutMouseEvent *qemu_put_mouse_event;
477 static void *qemu_put_mouse_event_opaque;
479 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
481 qemu_put_kbd_event_opaque = opaque;
482 qemu_put_kbd_event = func;
485 void qemu_add_mouse_event_handler(QEMUPutMouseEvent *func, void *opaque)
487 qemu_put_mouse_event_opaque = opaque;
488 qemu_put_mouse_event = func;
491 void kbd_put_keycode(int keycode)
493 if (qemu_put_kbd_event) {
494 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
498 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
500 if (qemu_put_mouse_event) {
501 qemu_put_mouse_event(qemu_put_mouse_event_opaque,
502 dx, dy, dz, buttons_state);
506 /***********************************************************/
509 #if defined(__powerpc__)
511 static inline uint32_t get_tbl(void)
514 asm volatile("mftb %0" : "=r" (tbl));
518 static inline uint32_t get_tbu(void)
521 asm volatile("mftbu %0" : "=r" (tbl));
525 int64_t cpu_get_real_ticks(void)
528 /* NOTE: we test if wrapping has occurred */
534 return ((int64_t)h << 32) | l;
537 #elif defined(__i386__)
539 int64_t cpu_get_real_ticks(void)
542 asm volatile ("rdtsc" : "=A" (val));
546 #elif defined(__x86_64__)
548 int64_t cpu_get_real_ticks(void)
552 asm volatile("rdtsc" : "=a" (low), "=d" (high));
559 #elif defined(__ia64)
561 int64_t cpu_get_real_ticks(void)
564 asm volatile ("mov %0 = ar.itc" : "=r"(val) :: "memory");
568 #elif defined(__s390__)
570 int64_t cpu_get_real_ticks(void)
573 asm volatile("stck 0(%1)" : "=m" (val) : "a" (&val) : "cc");
578 #error unsupported CPU
581 static int64_t cpu_ticks_offset;
582 static int cpu_ticks_enabled;
584 static inline int64_t cpu_get_ticks(void)
586 if (!cpu_ticks_enabled) {
587 return cpu_ticks_offset;
589 return cpu_get_real_ticks() + cpu_ticks_offset;
593 /* enable cpu_get_ticks() */
594 void cpu_enable_ticks(void)
596 if (!cpu_ticks_enabled) {
597 cpu_ticks_offset -= cpu_get_real_ticks();
598 cpu_ticks_enabled = 1;
602 /* disable cpu_get_ticks() : the clock is stopped. You must not call
603 cpu_get_ticks() after that. */
604 void cpu_disable_ticks(void)
606 if (cpu_ticks_enabled) {
607 cpu_ticks_offset = cpu_get_ticks();
608 cpu_ticks_enabled = 0;
612 static int64_t get_clock(void)
617 return ((int64_t)tb.time * 1000 + (int64_t)tb.millitm) * 1000;
620 gettimeofday(&tv, NULL);
621 return tv.tv_sec * 1000000LL + tv.tv_usec;
625 void cpu_calibrate_ticks(void)
630 ticks = cpu_get_real_ticks();
636 usec = get_clock() - usec;
637 ticks = cpu_get_real_ticks() - ticks;
638 ticks_per_sec = (ticks * 1000000LL + (usec >> 1)) / usec;
641 /* compute with 96 bit intermediate result: (a*b)/c */
642 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
647 #ifdef WORDS_BIGENDIAN
657 rl = (uint64_t)u.l.low * (uint64_t)b;
658 rh = (uint64_t)u.l.high * (uint64_t)b;
661 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
665 #define QEMU_TIMER_REALTIME 0
666 #define QEMU_TIMER_VIRTUAL 1
670 /* XXX: add frequency */
678 struct QEMUTimer *next;
684 static QEMUTimer *active_timers[2];
686 static MMRESULT timerID;
688 /* frequency of the times() clock tick */
689 static int timer_freq;
692 QEMUClock *qemu_new_clock(int type)
695 clock = qemu_mallocz(sizeof(QEMUClock));
702 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
706 ts = qemu_mallocz(sizeof(QEMUTimer));
713 void qemu_free_timer(QEMUTimer *ts)
718 /* stop a timer, but do not dealloc it */
719 void qemu_del_timer(QEMUTimer *ts)
723 /* NOTE: this code must be signal safe because
724 qemu_timer_expired() can be called from a signal. */
725 pt = &active_timers[ts->clock->type];
738 /* modify the current timer so that it will be fired when current_time
739 >= expire_time. The corresponding callback will be called. */
740 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
746 /* add the timer in the sorted list */
747 /* NOTE: this code must be signal safe because
748 qemu_timer_expired() can be called from a signal. */
749 pt = &active_timers[ts->clock->type];
754 if (t->expire_time > expire_time)
758 ts->expire_time = expire_time;
763 int qemu_timer_pending(QEMUTimer *ts)
766 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
773 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
777 return (timer_head->expire_time <= current_time);
780 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
786 if (!ts || ts->expire_time > current_time)
788 /* remove timer from the list before calling the callback */
789 *ptimer_head = ts->next;
792 /* run the callback (the timer list can be modified) */
797 int64_t qemu_get_clock(QEMUClock *clock)
799 switch(clock->type) {
800 case QEMU_TIMER_REALTIME:
802 return GetTickCount();
807 /* Note that using gettimeofday() is not a good solution
808 for timers because its value change when the date is
810 if (timer_freq == 100) {
811 return times(&tp) * 10;
813 return ((int64_t)times(&tp) * 1000) / timer_freq;
818 case QEMU_TIMER_VIRTUAL:
819 return cpu_get_ticks();
824 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
826 uint64_t expire_time;
828 if (qemu_timer_pending(ts)) {
829 expire_time = ts->expire_time;
833 qemu_put_be64(f, expire_time);
836 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
838 uint64_t expire_time;
840 expire_time = qemu_get_be64(f);
841 if (expire_time != -1) {
842 qemu_mod_timer(ts, expire_time);
848 static void timer_save(QEMUFile *f, void *opaque)
850 if (cpu_ticks_enabled) {
851 hw_error("cannot save state if virtual timers are running");
853 qemu_put_be64s(f, &cpu_ticks_offset);
854 qemu_put_be64s(f, &ticks_per_sec);
857 static int timer_load(QEMUFile *f, void *opaque, int version_id)
861 if (cpu_ticks_enabled) {
864 qemu_get_be64s(f, &cpu_ticks_offset);
865 qemu_get_be64s(f, &ticks_per_sec);
870 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
871 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
873 static void host_alarm_handler(int host_signum)
877 #define DISP_FREQ 1000
879 static int64_t delta_min = INT64_MAX;
880 static int64_t delta_max, delta_cum, last_clock, delta, ti;
882 ti = qemu_get_clock(vm_clock);
883 if (last_clock != 0) {
884 delta = ti - last_clock;
885 if (delta < delta_min)
887 if (delta > delta_max)
890 if (++count == DISP_FREQ) {
891 printf("timer: min=%lld us max=%lld us avg=%lld us avg_freq=%0.3f Hz\n",
892 muldiv64(delta_min, 1000000, ticks_per_sec),
893 muldiv64(delta_max, 1000000, ticks_per_sec),
894 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
895 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
897 delta_min = INT64_MAX;
905 if (qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
906 qemu_get_clock(vm_clock)) ||
907 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
908 qemu_get_clock(rt_clock))) {
909 CPUState *env = cpu_single_env;
911 /* stop the currently executing cpu because a timer occured */
912 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
914 if (env->kqemu_enabled) {
915 kqemu_cpu_interrupt(env);
924 #if defined(__linux__)
926 #define RTC_FREQ 1024
930 static int start_rtc_timer(void)
932 rtc_fd = open("/dev/rtc", O_RDONLY);
935 if (ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
936 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
937 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
938 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
941 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
946 pit_min_timer_count = PIT_FREQ / RTC_FREQ;
952 static int start_rtc_timer(void)
957 #endif /* !defined(__linux__) */
959 #endif /* !defined(_WIN32) */
961 static void init_timers(void)
963 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
964 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
969 timerID = timeSetEvent(1, // interval (ms)
971 host_alarm_handler, // function
972 (DWORD)&count, // user parameter
973 TIME_PERIODIC | TIME_CALLBACK_FUNCTION);
975 perror("failed timer alarm");
979 pit_min_timer_count = ((uint64_t)10000 * PIT_FREQ) / 1000000;
982 struct sigaction act;
983 struct itimerval itv;
985 /* get times() syscall frequency */
986 timer_freq = sysconf(_SC_CLK_TCK);
989 sigfillset(&act.sa_mask);
991 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
992 act.sa_flags |= SA_ONSTACK;
994 act.sa_handler = host_alarm_handler;
995 sigaction(SIGALRM, &act, NULL);
997 itv.it_interval.tv_sec = 0;
998 itv.it_interval.tv_usec = 999; /* for i386 kernel 2.6 to get 1 ms */
999 itv.it_value.tv_sec = 0;
1000 itv.it_value.tv_usec = 10 * 1000;
1001 setitimer(ITIMER_REAL, &itv, NULL);
1002 /* we probe the tick duration of the kernel to inform the user if
1003 the emulated kernel requested a too high timer frequency */
1004 getitimer(ITIMER_REAL, &itv);
1006 #if defined(__linux__)
1007 if (itv.it_interval.tv_usec > 1000) {
1008 /* try to use /dev/rtc to have a faster timer */
1009 if (start_rtc_timer() < 0)
1011 /* disable itimer */
1012 itv.it_interval.tv_sec = 0;
1013 itv.it_interval.tv_usec = 0;
1014 itv.it_value.tv_sec = 0;
1015 itv.it_value.tv_usec = 0;
1016 setitimer(ITIMER_REAL, &itv, NULL);
1019 sigaction(SIGIO, &act, NULL);
1020 fcntl(rtc_fd, F_SETFL, O_ASYNC);
1021 fcntl(rtc_fd, F_SETOWN, getpid());
1023 #endif /* defined(__linux__) */
1026 pit_min_timer_count = ((uint64_t)itv.it_interval.tv_usec *
1027 PIT_FREQ) / 1000000;
1033 void quit_timers(void)
1036 timeKillEvent(timerID);
1040 /***********************************************************/
1041 /* character device */
1043 int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1045 return s->chr_write(s, buf, len);
1048 int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1052 return s->chr_ioctl(s, cmd, arg);
1055 void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1060 vsnprintf(buf, sizeof(buf), fmt, ap);
1061 qemu_chr_write(s, buf, strlen(buf));
1065 void qemu_chr_send_event(CharDriverState *s, int event)
1067 if (s->chr_send_event)
1068 s->chr_send_event(s, event);
1071 void qemu_chr_add_read_handler(CharDriverState *s,
1072 IOCanRWHandler *fd_can_read,
1073 IOReadHandler *fd_read, void *opaque)
1075 s->chr_add_read_handler(s, fd_can_read, fd_read, opaque);
1078 void qemu_chr_add_event_handler(CharDriverState *s, IOEventHandler *chr_event)
1080 s->chr_event = chr_event;
1083 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1088 static void null_chr_add_read_handler(CharDriverState *chr,
1089 IOCanRWHandler *fd_can_read,
1090 IOReadHandler *fd_read, void *opaque)
1094 CharDriverState *qemu_chr_open_null(void)
1096 CharDriverState *chr;
1098 chr = qemu_mallocz(sizeof(CharDriverState));
1101 chr->chr_write = null_chr_write;
1102 chr->chr_add_read_handler = null_chr_add_read_handler;
1108 #define socket_error() WSAGetLastError()
1110 #define EWOULDBLOCK WSAEWOULDBLOCK
1111 #define EINTR WSAEINTR
1112 #define EINPROGRESS WSAEINPROGRESS
1114 static void socket_cleanup(void)
1119 static int socket_init(void)
1124 ret = WSAStartup(MAKEWORD(2,2), &Data);
1126 err = WSAGetLastError();
1127 fprintf(stderr, "WSAStartup: %d\n", err);
1130 atexit(socket_cleanup);
1134 static int send_all(int fd, const uint8_t *buf, int len1)
1140 ret = send(fd, buf, len, 0);
1143 errno = WSAGetLastError();
1144 if (errno != WSAEWOULDBLOCK) {
1147 } else if (ret == 0) {
1157 void socket_set_nonblock(int fd)
1159 unsigned long opt = 1;
1160 ioctlsocket(fd, FIONBIO, &opt);
1165 #define socket_error() errno
1166 #define closesocket(s) close(s)
1168 static int unix_write(int fd, const uint8_t *buf, int len1)
1174 ret = write(fd, buf, len);
1176 if (errno != EINTR && errno != EAGAIN)
1178 } else if (ret == 0) {
1188 static inline int send_all(int fd, const uint8_t *buf, int len1)
1190 return unix_write(fd, buf, len1);
1193 void socket_set_nonblock(int fd)
1195 fcntl(fd, F_SETFL, O_NONBLOCK);
1197 #endif /* !_WIN32 */
1203 IOCanRWHandler *fd_can_read;
1204 IOReadHandler *fd_read;
1209 #define STDIO_MAX_CLIENTS 2
1211 static int stdio_nb_clients;
1212 static CharDriverState *stdio_clients[STDIO_MAX_CLIENTS];
1214 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1216 FDCharDriver *s = chr->opaque;
1217 return unix_write(s->fd_out, buf, len);
1220 static int fd_chr_read_poll(void *opaque)
1222 CharDriverState *chr = opaque;
1223 FDCharDriver *s = chr->opaque;
1225 s->max_size = s->fd_can_read(s->fd_opaque);
1229 static void fd_chr_read(void *opaque)
1231 CharDriverState *chr = opaque;
1232 FDCharDriver *s = chr->opaque;
1237 if (len > s->max_size)
1241 size = read(s->fd_in, buf, len);
1243 s->fd_read(s->fd_opaque, buf, size);
1247 static void fd_chr_add_read_handler(CharDriverState *chr,
1248 IOCanRWHandler *fd_can_read,
1249 IOReadHandler *fd_read, void *opaque)
1251 FDCharDriver *s = chr->opaque;
1253 if (s->fd_in >= 0) {
1254 s->fd_can_read = fd_can_read;
1255 s->fd_read = fd_read;
1256 s->fd_opaque = opaque;
1257 if (nographic && s->fd_in == 0) {
1259 qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
1260 fd_chr_read, NULL, chr);
1265 /* open a character device to a unix fd */
1266 CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
1268 CharDriverState *chr;
1271 chr = qemu_mallocz(sizeof(CharDriverState));
1274 s = qemu_mallocz(sizeof(FDCharDriver));
1282 chr->chr_write = fd_chr_write;
1283 chr->chr_add_read_handler = fd_chr_add_read_handler;
1287 CharDriverState *qemu_chr_open_file_out(const char *file_out)
1291 fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY);
1294 return qemu_chr_open_fd(-1, fd_out);
1297 CharDriverState *qemu_chr_open_pipe(const char *filename)
1301 fd = open(filename, O_RDWR | O_BINARY);
1304 return qemu_chr_open_fd(fd, fd);
1308 /* for STDIO, we handle the case where several clients use it
1311 #define TERM_ESCAPE 0x01 /* ctrl-a is used for escape */
1313 #define TERM_FIFO_MAX_SIZE 1
1315 static int term_got_escape, client_index;
1316 static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
1319 void term_print_help(void)
1322 "C-a h print this help\n"
1323 "C-a x exit emulator\n"
1324 "C-a s save disk data back to file (if -snapshot)\n"
1325 "C-a b send break (magic sysrq)\n"
1326 "C-a c switch between console and monitor\n"
1327 "C-a C-a send C-a\n"
1331 /* called when a char is received */
1332 static void stdio_received_byte(int ch)
1334 if (term_got_escape) {
1335 term_got_escape = 0;
1346 for (i = 0; i < MAX_DISKS; i++) {
1348 bdrv_commit(bs_table[i]);
1353 if (client_index < stdio_nb_clients) {
1354 CharDriverState *chr;
1357 chr = stdio_clients[client_index];
1359 chr->chr_event(s->fd_opaque, CHR_EVENT_BREAK);
1364 if (client_index >= stdio_nb_clients)
1366 if (client_index == 0) {
1367 /* send a new line in the monitor to get the prompt */
1375 } else if (ch == TERM_ESCAPE) {
1376 term_got_escape = 1;
1379 if (client_index < stdio_nb_clients) {
1381 CharDriverState *chr;
1384 chr = stdio_clients[client_index];
1386 if (s->fd_can_read(s->fd_opaque) > 0) {
1388 s->fd_read(s->fd_opaque, buf, 1);
1389 } else if (term_fifo_size == 0) {
1390 term_fifo[term_fifo_size++] = ch;
1396 static int stdio_read_poll(void *opaque)
1398 CharDriverState *chr;
1401 if (client_index < stdio_nb_clients) {
1402 chr = stdio_clients[client_index];
1404 /* try to flush the queue if needed */
1405 if (term_fifo_size != 0 && s->fd_can_read(s->fd_opaque) > 0) {
1406 s->fd_read(s->fd_opaque, term_fifo, 1);
1409 /* see if we can absorb more chars */
1410 if (term_fifo_size == 0)
1419 static void stdio_read(void *opaque)
1424 size = read(0, buf, 1);
1426 stdio_received_byte(buf[0]);
1429 /* init terminal so that we can grab keys */
1430 static struct termios oldtty;
1431 static int old_fd0_flags;
1433 static void term_exit(void)
1435 tcsetattr (0, TCSANOW, &oldtty);
1436 fcntl(0, F_SETFL, old_fd0_flags);
1439 static void term_init(void)
1443 tcgetattr (0, &tty);
1445 old_fd0_flags = fcntl(0, F_GETFL);
1447 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1448 |INLCR|IGNCR|ICRNL|IXON);
1449 tty.c_oflag |= OPOST;
1450 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1451 /* if graphical mode, we allow Ctrl-C handling */
1453 tty.c_lflag &= ~ISIG;
1454 tty.c_cflag &= ~(CSIZE|PARENB);
1457 tty.c_cc[VTIME] = 0;
1459 tcsetattr (0, TCSANOW, &tty);
1463 fcntl(0, F_SETFL, O_NONBLOCK);
1466 CharDriverState *qemu_chr_open_stdio(void)
1468 CharDriverState *chr;
1471 if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
1473 chr = qemu_chr_open_fd(0, 1);
1474 if (stdio_nb_clients == 0)
1475 qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, NULL);
1476 client_index = stdio_nb_clients;
1478 if (stdio_nb_clients != 0)
1480 chr = qemu_chr_open_fd(0, 1);
1482 stdio_clients[stdio_nb_clients++] = chr;
1483 if (stdio_nb_clients == 1) {
1484 /* set the terminal in raw mode */
1490 #if defined(__linux__)
1491 CharDriverState *qemu_chr_open_pty(void)
1494 char slave_name[1024];
1495 int master_fd, slave_fd;
1497 /* Not satisfying */
1498 if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
1502 /* Disabling local echo and line-buffered output */
1503 tcgetattr (master_fd, &tty);
1504 tty.c_lflag &= ~(ECHO|ICANON|ISIG);
1506 tty.c_cc[VTIME] = 0;
1507 tcsetattr (master_fd, TCSAFLUSH, &tty);
1509 fprintf(stderr, "char device redirected to %s\n", slave_name);
1510 return qemu_chr_open_fd(master_fd, master_fd);
1513 static void tty_serial_init(int fd, int speed,
1514 int parity, int data_bits, int stop_bits)
1520 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1521 speed, parity, data_bits, stop_bits);
1523 tcgetattr (fd, &tty);
1565 cfsetispeed(&tty, spd);
1566 cfsetospeed(&tty, spd);
1568 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1569 |INLCR|IGNCR|ICRNL|IXON);
1570 tty.c_oflag |= OPOST;
1571 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1572 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS);
1593 tty.c_cflag |= PARENB;
1596 tty.c_cflag |= PARENB | PARODD;
1600 tcsetattr (fd, TCSANOW, &tty);
1603 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1605 FDCharDriver *s = chr->opaque;
1608 case CHR_IOCTL_SERIAL_SET_PARAMS:
1610 QEMUSerialSetParams *ssp = arg;
1611 tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
1612 ssp->data_bits, ssp->stop_bits);
1615 case CHR_IOCTL_SERIAL_SET_BREAK:
1617 int enable = *(int *)arg;
1619 tcsendbreak(s->fd_in, 1);
1628 CharDriverState *qemu_chr_open_tty(const char *filename)
1630 CharDriverState *chr;
1633 fd = open(filename, O_RDWR | O_NONBLOCK);
1636 fcntl(fd, F_SETFL, O_NONBLOCK);
1637 tty_serial_init(fd, 115200, 'N', 8, 1);
1638 chr = qemu_chr_open_fd(fd, fd);
1641 chr->chr_ioctl = tty_serial_ioctl;
1645 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1647 int fd = (int)chr->opaque;
1651 case CHR_IOCTL_PP_READ_DATA:
1652 if (ioctl(fd, PPRDATA, &b) < 0)
1654 *(uint8_t *)arg = b;
1656 case CHR_IOCTL_PP_WRITE_DATA:
1657 b = *(uint8_t *)arg;
1658 if (ioctl(fd, PPWDATA, &b) < 0)
1661 case CHR_IOCTL_PP_READ_CONTROL:
1662 if (ioctl(fd, PPRCONTROL, &b) < 0)
1664 *(uint8_t *)arg = b;
1666 case CHR_IOCTL_PP_WRITE_CONTROL:
1667 b = *(uint8_t *)arg;
1668 if (ioctl(fd, PPWCONTROL, &b) < 0)
1671 case CHR_IOCTL_PP_READ_STATUS:
1672 if (ioctl(fd, PPRSTATUS, &b) < 0)
1674 *(uint8_t *)arg = b;
1682 CharDriverState *qemu_chr_open_pp(const char *filename)
1684 CharDriverState *chr;
1687 fd = open(filename, O_RDWR);
1691 if (ioctl(fd, PPCLAIM) < 0) {
1696 chr = qemu_mallocz(sizeof(CharDriverState));
1701 chr->opaque = (void *)fd;
1702 chr->chr_write = null_chr_write;
1703 chr->chr_add_read_handler = null_chr_add_read_handler;
1704 chr->chr_ioctl = pp_ioctl;
1709 CharDriverState *qemu_chr_open_pty(void)
1715 #endif /* !defined(_WIN32) */
1717 CharDriverState *qemu_chr_open(const char *filename)
1723 if (!strcmp(filename, "vc")) {
1724 return text_console_init(&display_state);
1725 } else if (!strcmp(filename, "null")) {
1726 return qemu_chr_open_null();
1729 if (strstart(filename, "file:", &p)) {
1730 return qemu_chr_open_file_out(p);
1731 } else if (strstart(filename, "pipe:", &p)) {
1732 return qemu_chr_open_pipe(p);
1733 } else if (!strcmp(filename, "pty")) {
1734 return qemu_chr_open_pty();
1735 } else if (!strcmp(filename, "stdio")) {
1736 return qemu_chr_open_stdio();
1739 #if defined(__linux__)
1740 if (strstart(filename, "/dev/parport", NULL)) {
1741 return qemu_chr_open_pp(filename);
1743 if (strstart(filename, "/dev/", NULL)) {
1744 return qemu_chr_open_tty(filename);
1752 /***********************************************************/
1753 /* network device redirectors */
1755 void hex_dump(FILE *f, const uint8_t *buf, int size)
1759 for(i=0;i<size;i+=16) {
1763 fprintf(f, "%08x ", i);
1766 fprintf(f, " %02x", buf[i+j]);
1771 for(j=0;j<len;j++) {
1773 if (c < ' ' || c > '~')
1775 fprintf(f, "%c", c);
1781 static int parse_macaddr(uint8_t *macaddr, const char *p)
1784 for(i = 0; i < 6; i++) {
1785 macaddr[i] = strtol(p, (char **)&p, 16);
1798 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
1803 p1 = strchr(p, sep);
1809 if (len > buf_size - 1)
1811 memcpy(buf, p, len);
1818 int parse_host_port(struct sockaddr_in *saddr, const char *str)
1826 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
1828 saddr->sin_family = AF_INET;
1829 if (buf[0] == '\0') {
1830 saddr->sin_addr.s_addr = 0;
1832 if (isdigit(buf[0])) {
1833 if (!inet_aton(buf, &saddr->sin_addr))
1836 if ((he = gethostbyname(buf)) == NULL)
1838 saddr->sin_addr = *(struct in_addr *)he->h_addr;
1841 port = strtol(p, (char **)&r, 0);
1844 saddr->sin_port = htons(port);
1848 /* find or alloc a new VLAN */
1849 VLANState *qemu_find_vlan(int id)
1851 VLANState **pvlan, *vlan;
1852 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
1856 vlan = qemu_mallocz(sizeof(VLANState));
1861 pvlan = &first_vlan;
1862 while (*pvlan != NULL)
1863 pvlan = &(*pvlan)->next;
1868 VLANClientState *qemu_new_vlan_client(VLANState *vlan,
1869 IOReadHandler *fd_read,
1870 IOCanRWHandler *fd_can_read,
1873 VLANClientState *vc, **pvc;
1874 vc = qemu_mallocz(sizeof(VLANClientState));
1877 vc->fd_read = fd_read;
1878 vc->fd_can_read = fd_can_read;
1879 vc->opaque = opaque;
1883 pvc = &vlan->first_client;
1884 while (*pvc != NULL)
1885 pvc = &(*pvc)->next;
1890 int qemu_can_send_packet(VLANClientState *vc1)
1892 VLANState *vlan = vc1->vlan;
1893 VLANClientState *vc;
1895 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
1897 if (vc->fd_can_read && !vc->fd_can_read(vc->opaque))
1904 void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
1906 VLANState *vlan = vc1->vlan;
1907 VLANClientState *vc;
1910 printf("vlan %d send:\n", vlan->id);
1911 hex_dump(stdout, buf, size);
1913 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
1915 vc->fd_read(vc->opaque, buf, size);
1920 #if defined(CONFIG_SLIRP)
1922 /* slirp network adapter */
1924 static int slirp_inited;
1925 static VLANClientState *slirp_vc;
1927 int slirp_can_output(void)
1929 return !slirp_vc || qemu_can_send_packet(slirp_vc);
1932 void slirp_output(const uint8_t *pkt, int pkt_len)
1935 printf("slirp output:\n");
1936 hex_dump(stdout, pkt, pkt_len);
1940 qemu_send_packet(slirp_vc, pkt, pkt_len);
1943 static void slirp_receive(void *opaque, const uint8_t *buf, int size)
1946 printf("slirp input:\n");
1947 hex_dump(stdout, buf, size);
1949 slirp_input(buf, size);
1952 static int net_slirp_init(VLANState *vlan)
1954 if (!slirp_inited) {
1958 slirp_vc = qemu_new_vlan_client(vlan,
1959 slirp_receive, NULL, NULL);
1960 snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
1964 static void net_slirp_redir(const char *redir_str)
1969 struct in_addr guest_addr;
1970 int host_port, guest_port;
1972 if (!slirp_inited) {
1978 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
1980 if (!strcmp(buf, "tcp")) {
1982 } else if (!strcmp(buf, "udp")) {
1988 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
1990 host_port = strtol(buf, &r, 0);
1994 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
1996 if (buf[0] == '\0') {
1997 pstrcpy(buf, sizeof(buf), "10.0.2.15");
1999 if (!inet_aton(buf, &guest_addr))
2002 guest_port = strtol(p, &r, 0);
2006 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
2007 fprintf(stderr, "qemu: could not set up redirection\n");
2012 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
2020 static void smb_exit(void)
2024 char filename[1024];
2026 /* erase all the files in the directory */
2027 d = opendir(smb_dir);
2032 if (strcmp(de->d_name, ".") != 0 &&
2033 strcmp(de->d_name, "..") != 0) {
2034 snprintf(filename, sizeof(filename), "%s/%s",
2035 smb_dir, de->d_name);
2043 /* automatic user mode samba server configuration */
2044 void net_slirp_smb(const char *exported_dir)
2046 char smb_conf[1024];
2047 char smb_cmdline[1024];
2050 if (!slirp_inited) {
2055 /* XXX: better tmp dir construction */
2056 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
2057 if (mkdir(smb_dir, 0700) < 0) {
2058 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
2061 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
2063 f = fopen(smb_conf, "w");
2065 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
2072 "socket address=127.0.0.1\n"
2073 "pid directory=%s\n"
2074 "lock directory=%s\n"
2075 "log file=%s/log.smbd\n"
2076 "smb passwd file=%s/smbpasswd\n"
2077 "security = share\n"
2092 snprintf(smb_cmdline, sizeof(smb_cmdline), "/usr/sbin/smbd -s %s",
2095 slirp_add_exec(0, smb_cmdline, 4, 139);
2098 #endif /* !defined(_WIN32) */
2100 #endif /* CONFIG_SLIRP */
2102 #if !defined(_WIN32)
2104 typedef struct TAPState {
2105 VLANClientState *vc;
2109 static void tap_receive(void *opaque, const uint8_t *buf, int size)
2111 TAPState *s = opaque;
2114 ret = write(s->fd, buf, size);
2115 if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
2122 static void tap_send(void *opaque)
2124 TAPState *s = opaque;
2128 size = read(s->fd, buf, sizeof(buf));
2130 qemu_send_packet(s->vc, buf, size);
2136 static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
2140 s = qemu_mallocz(sizeof(TAPState));
2144 s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
2145 qemu_set_fd_handler(s->fd, tap_send, NULL, s);
2146 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
2151 static int tap_open(char *ifname, int ifname_size)
2157 fd = open("/dev/tap", O_RDWR);
2159 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
2164 dev = devname(s.st_rdev, S_IFCHR);
2165 pstrcpy(ifname, ifname_size, dev);
2167 fcntl(fd, F_SETFL, O_NONBLOCK);
2171 static int tap_open(char *ifname, int ifname_size)
2176 fd = open("/dev/net/tun", O_RDWR);
2178 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
2181 memset(&ifr, 0, sizeof(ifr));
2182 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
2183 if (ifname[0] != '\0')
2184 pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
2186 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
2187 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
2189 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
2193 pstrcpy(ifname, ifname_size, ifr.ifr_name);
2194 fcntl(fd, F_SETFL, O_NONBLOCK);
2199 static int net_tap_init(VLANState *vlan, const char *ifname1,
2200 const char *setup_script)
2203 int pid, status, fd;
2208 if (ifname1 != NULL)
2209 pstrcpy(ifname, sizeof(ifname), ifname1);
2212 fd = tap_open(ifname, sizeof(ifname));
2218 if (setup_script[0] != '\0') {
2219 /* try to launch network init script */
2224 *parg++ = (char *)setup_script;
2227 execv(setup_script, args);
2230 while (waitpid(pid, &status, 0) != pid);
2231 if (!WIFEXITED(status) ||
2232 WEXITSTATUS(status) != 0) {
2233 fprintf(stderr, "%s: could not launch network script\n",
2239 s = net_tap_fd_init(vlan, fd);
2242 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
2243 "tap: ifname=%s setup_script=%s", ifname, setup_script);
2247 #endif /* !_WIN32 */
2249 /* network connection */
2250 typedef struct NetSocketState {
2251 VLANClientState *vc;
2253 int state; /* 0 = getting length, 1 = getting data */
2257 struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
2260 typedef struct NetSocketListenState {
2263 } NetSocketListenState;
2265 /* XXX: we consider we can send the whole packet without blocking */
2266 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
2268 NetSocketState *s = opaque;
2272 send_all(s->fd, (const uint8_t *)&len, sizeof(len));
2273 send_all(s->fd, buf, size);
2276 static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
2278 NetSocketState *s = opaque;
2279 sendto(s->fd, buf, size, 0,
2280 (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
2283 static void net_socket_send(void *opaque)
2285 NetSocketState *s = opaque;
2290 size = recv(s->fd, buf1, sizeof(buf1), 0);
2292 err = socket_error();
2293 if (err != EWOULDBLOCK)
2295 } else if (size == 0) {
2296 /* end of connection */
2298 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2304 /* reassemble a packet from the network */
2310 memcpy(s->buf + s->index, buf, l);
2314 if (s->index == 4) {
2316 s->packet_len = ntohl(*(uint32_t *)s->buf);
2322 l = s->packet_len - s->index;
2325 memcpy(s->buf + s->index, buf, l);
2329 if (s->index >= s->packet_len) {
2330 qemu_send_packet(s->vc, s->buf, s->packet_len);
2339 static void net_socket_send_dgram(void *opaque)
2341 NetSocketState *s = opaque;
2344 size = recv(s->fd, s->buf, sizeof(s->buf), 0);
2348 /* end of connection */
2349 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2352 qemu_send_packet(s->vc, s->buf, size);
2355 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
2360 if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
2361 fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
2362 inet_ntoa(mcastaddr->sin_addr),
2363 (int)ntohl(mcastaddr->sin_addr.s_addr));
2367 fd = socket(PF_INET, SOCK_DGRAM, 0);
2369 perror("socket(PF_INET, SOCK_DGRAM)");
2374 ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
2375 (const char *)&val, sizeof(val));
2377 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
2381 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
2387 /* Add host to multicast group */
2388 imr.imr_multiaddr = mcastaddr->sin_addr;
2389 imr.imr_interface.s_addr = htonl(INADDR_ANY);
2391 ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
2392 (const char *)&imr, sizeof(struct ip_mreq));
2394 perror("setsockopt(IP_ADD_MEMBERSHIP)");
2398 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
2400 ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
2401 (const char *)&val, sizeof(val));
2403 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
2407 socket_set_nonblock(fd);
2410 if (fd>=0) close(fd);
2414 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd,
2417 struct sockaddr_in saddr;
2419 socklen_t saddr_len;
2422 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
2423 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
2424 * by ONLY ONE process: we must "clone" this dgram socket --jjo
2428 if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
2430 if (saddr.sin_addr.s_addr==0) {
2431 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
2435 /* clone dgram socket */
2436 newfd = net_socket_mcast_create(&saddr);
2438 /* error already reported by net_socket_mcast_create() */
2442 /* clone newfd to fd, close newfd */
2447 fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
2448 fd, strerror(errno));
2453 s = qemu_mallocz(sizeof(NetSocketState));
2458 s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
2459 qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
2461 /* mcast: save bound address as dst */
2462 if (is_connected) s->dgram_dst=saddr;
2464 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
2465 "socket: fd=%d (%s mcast=%s:%d)",
2466 fd, is_connected? "cloned" : "",
2467 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
2471 static void net_socket_connect(void *opaque)
2473 NetSocketState *s = opaque;
2474 qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
2477 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd,
2481 s = qemu_mallocz(sizeof(NetSocketState));
2485 s->vc = qemu_new_vlan_client(vlan,
2486 net_socket_receive, NULL, s);
2487 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
2488 "socket: fd=%d", fd);
2490 net_socket_connect(s);
2492 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
2497 static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
2500 int so_type=-1, optlen=sizeof(so_type);
2502 if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type, &optlen)< 0) {
2503 fprintf(stderr, "qemu: error: setsockopt(SO_TYPE) for fd=%d failed\n", fd);
2508 return net_socket_fd_init_dgram(vlan, fd, is_connected);
2510 return net_socket_fd_init_stream(vlan, fd, is_connected);
2512 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
2513 fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
2514 return net_socket_fd_init_stream(vlan, fd, is_connected);
2519 static void net_socket_accept(void *opaque)
2521 NetSocketListenState *s = opaque;
2523 struct sockaddr_in saddr;
2528 len = sizeof(saddr);
2529 fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
2530 if (fd < 0 && errno != EINTR) {
2532 } else if (fd >= 0) {
2536 s1 = net_socket_fd_init(s->vlan, fd, 1);
2540 snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
2541 "socket: connection from %s:%d",
2542 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
2546 static int net_socket_listen_init(VLANState *vlan, const char *host_str)
2548 NetSocketListenState *s;
2550 struct sockaddr_in saddr;
2552 if (parse_host_port(&saddr, host_str) < 0)
2555 s = qemu_mallocz(sizeof(NetSocketListenState));
2559 fd = socket(PF_INET, SOCK_STREAM, 0);
2564 socket_set_nonblock(fd);
2566 /* allow fast reuse */
2568 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
2570 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
2575 ret = listen(fd, 0);
2582 qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
2586 static int net_socket_connect_init(VLANState *vlan, const char *host_str)
2589 int fd, connected, ret, err;
2590 struct sockaddr_in saddr;
2592 if (parse_host_port(&saddr, host_str) < 0)
2595 fd = socket(PF_INET, SOCK_STREAM, 0);
2600 socket_set_nonblock(fd);
2604 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
2606 err = socket_error();
2607 if (err == EINTR || err == EWOULDBLOCK) {
2608 } else if (err == EINPROGRESS) {
2620 s = net_socket_fd_init(vlan, fd, connected);
2623 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
2624 "socket: connect to %s:%d",
2625 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
2629 static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
2633 struct sockaddr_in saddr;
2635 if (parse_host_port(&saddr, host_str) < 0)
2639 fd = net_socket_mcast_create(&saddr);
2643 s = net_socket_fd_init(vlan, fd, 0);
2647 s->dgram_dst = saddr;
2649 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
2650 "socket: mcast=%s:%d",
2651 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
2656 static int get_param_value(char *buf, int buf_size,
2657 const char *tag, const char *str)
2666 while (*p != '\0' && *p != '=') {
2667 if ((q - option) < sizeof(option) - 1)
2675 if (!strcmp(tag, option)) {
2677 while (*p != '\0' && *p != ',') {
2678 if ((q - buf) < buf_size - 1)
2685 while (*p != '\0' && *p != ',') {
2696 int net_client_init(const char *str)
2707 while (*p != '\0' && *p != ',') {
2708 if ((q - device) < sizeof(device) - 1)
2716 if (get_param_value(buf, sizeof(buf), "vlan", p)) {
2717 vlan_id = strtol(buf, NULL, 0);
2719 vlan = qemu_find_vlan(vlan_id);
2721 fprintf(stderr, "Could not create vlan %d\n", vlan_id);
2724 if (!strcmp(device, "nic")) {
2728 if (nb_nics >= MAX_NICS) {
2729 fprintf(stderr, "Too Many NICs\n");
2732 nd = &nd_table[nb_nics];
2733 macaddr = nd->macaddr;
2739 macaddr[5] = 0x56 + nb_nics;
2741 if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
2742 if (parse_macaddr(macaddr, buf) < 0) {
2743 fprintf(stderr, "invalid syntax for ethernet address\n");
2747 if (get_param_value(buf, sizeof(buf), "model", p)) {
2748 nd->model = strdup(buf);
2754 if (!strcmp(device, "none")) {
2755 /* does nothing. It is needed to signal that no network cards
2760 if (!strcmp(device, "user")) {
2761 ret = net_slirp_init(vlan);
2765 if (!strcmp(device, "tap")) {
2767 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
2768 fprintf(stderr, "tap: no interface name\n");
2771 ret = tap_win32_init(vlan, ifname);
2774 if (!strcmp(device, "tap")) {
2776 char setup_script[1024];
2778 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
2779 fd = strtol(buf, NULL, 0);
2781 if (net_tap_fd_init(vlan, fd))
2784 get_param_value(ifname, sizeof(ifname), "ifname", p);
2785 if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
2786 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
2788 ret = net_tap_init(vlan, ifname, setup_script);
2792 if (!strcmp(device, "socket")) {
2793 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
2795 fd = strtol(buf, NULL, 0);
2797 if (net_socket_fd_init(vlan, fd, 1))
2799 } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
2800 ret = net_socket_listen_init(vlan, buf);
2801 } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
2802 ret = net_socket_connect_init(vlan, buf);
2803 } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
2804 ret = net_socket_mcast_init(vlan, buf);
2806 fprintf(stderr, "Unknown socket options: %s\n", p);
2811 fprintf(stderr, "Unknown network device: %s\n", device);
2815 fprintf(stderr, "Could not initialize device '%s'\n", device);
2821 void do_info_network(void)
2824 VLANClientState *vc;
2826 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
2827 term_printf("VLAN %d devices:\n", vlan->id);
2828 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
2829 term_printf(" %s\n", vc->info_str);
2833 /***********************************************************/
2836 static int usb_device_add(const char *devname)
2844 for(i = 0;i < MAX_VM_USB_PORTS; i++) {
2845 if (!vm_usb_ports[i]->dev)
2848 if (i == MAX_VM_USB_PORTS)
2851 if (strstart(devname, "host:", &p)) {
2852 dev = usb_host_device_open(p);
2855 } else if (!strcmp(devname, "mouse")) {
2856 dev = usb_mouse_init();
2862 usb_attach(vm_usb_ports[i], dev);
2866 static int usb_device_del(const char *devname)
2869 int bus_num, addr, i;
2875 p = strchr(devname, '.');
2878 bus_num = strtoul(devname, NULL, 0);
2879 addr = strtoul(p + 1, NULL, 0);
2882 for(i = 0;i < MAX_VM_USB_PORTS; i++) {
2883 dev = vm_usb_ports[i]->dev;
2884 if (dev && dev->addr == addr)
2887 if (i == MAX_VM_USB_PORTS)
2889 usb_attach(vm_usb_ports[i], NULL);
2893 void do_usb_add(const char *devname)
2896 ret = usb_device_add(devname);
2898 term_printf("Could not add USB device '%s'\n", devname);
2901 void do_usb_del(const char *devname)
2904 ret = usb_device_del(devname);
2906 term_printf("Could not remove USB device '%s'\n", devname);
2913 const char *speed_str;
2916 term_printf("USB support not enabled\n");
2920 for(i = 0; i < MAX_VM_USB_PORTS; i++) {
2921 dev = vm_usb_ports[i]->dev;
2923 term_printf("Hub port %d:\n", i);
2924 switch(dev->speed) {
2928 case USB_SPEED_FULL:
2931 case USB_SPEED_HIGH:
2938 term_printf(" Device %d.%d, speed %s Mb/s\n",
2939 0, dev->addr, speed_str);
2944 /***********************************************************/
2947 static char *pid_filename;
2949 /* Remove PID file. Called on normal exit */
2951 static void remove_pidfile(void)
2953 unlink (pid_filename);
2956 static void create_pidfile(const char *filename)
2958 struct stat pidstat;
2961 /* Try to write our PID to the named file */
2962 if (stat(filename, &pidstat) < 0) {
2963 if (errno == ENOENT) {
2964 if ((f = fopen (filename, "w")) == NULL) {
2965 perror("Opening pidfile");
2968 fprintf(f, "%d\n", getpid());
2970 pid_filename = qemu_strdup(filename);
2971 if (!pid_filename) {
2972 fprintf(stderr, "Could not save PID filename");
2975 atexit(remove_pidfile);
2978 fprintf(stderr, "%s already exists. Remove it and try again.\n",
2984 /***********************************************************/
2987 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
2991 static void dumb_resize(DisplayState *ds, int w, int h)
2995 static void dumb_refresh(DisplayState *ds)
2997 vga_update_display();
3000 void dumb_display_init(DisplayState *ds)
3005 ds->dpy_update = dumb_update;
3006 ds->dpy_resize = dumb_resize;
3007 ds->dpy_refresh = dumb_refresh;
3010 #if !defined(CONFIG_SOFTMMU)
3011 /***********************************************************/
3012 /* cpu signal handler */
3013 static void host_segv_handler(int host_signum, siginfo_t *info,
3016 if (cpu_signal_handler(host_signum, info, puc))
3018 if (stdio_nb_clients > 0)
3024 /***********************************************************/
3027 #define MAX_IO_HANDLERS 64
3029 typedef struct IOHandlerRecord {
3031 IOCanRWHandler *fd_read_poll;
3033 IOHandler *fd_write;
3035 /* temporary data */
3037 struct IOHandlerRecord *next;
3040 static IOHandlerRecord *first_io_handler;
3042 /* XXX: fd_read_poll should be suppressed, but an API change is
3043 necessary in the character devices to suppress fd_can_read(). */
3044 int qemu_set_fd_handler2(int fd,
3045 IOCanRWHandler *fd_read_poll,
3047 IOHandler *fd_write,
3050 IOHandlerRecord **pioh, *ioh;
3052 if (!fd_read && !fd_write) {
3053 pioh = &first_io_handler;
3058 if (ioh->fd == fd) {
3066 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3070 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
3073 ioh->next = first_io_handler;
3074 first_io_handler = ioh;
3077 ioh->fd_read_poll = fd_read_poll;
3078 ioh->fd_read = fd_read;
3079 ioh->fd_write = fd_write;
3080 ioh->opaque = opaque;
3085 int qemu_set_fd_handler(int fd,
3087 IOHandler *fd_write,
3090 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
3093 /***********************************************************/
3094 /* savevm/loadvm support */
3096 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
3098 fwrite(buf, 1, size, f);
3101 void qemu_put_byte(QEMUFile *f, int v)
3106 void qemu_put_be16(QEMUFile *f, unsigned int v)
3108 qemu_put_byte(f, v >> 8);
3109 qemu_put_byte(f, v);
3112 void qemu_put_be32(QEMUFile *f, unsigned int v)
3114 qemu_put_byte(f, v >> 24);
3115 qemu_put_byte(f, v >> 16);
3116 qemu_put_byte(f, v >> 8);
3117 qemu_put_byte(f, v);
3120 void qemu_put_be64(QEMUFile *f, uint64_t v)
3122 qemu_put_be32(f, v >> 32);
3123 qemu_put_be32(f, v);
3126 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size)
3128 return fread(buf, 1, size, f);
3131 int qemu_get_byte(QEMUFile *f)
3141 unsigned int qemu_get_be16(QEMUFile *f)
3144 v = qemu_get_byte(f) << 8;
3145 v |= qemu_get_byte(f);
3149 unsigned int qemu_get_be32(QEMUFile *f)
3152 v = qemu_get_byte(f) << 24;
3153 v |= qemu_get_byte(f) << 16;
3154 v |= qemu_get_byte(f) << 8;
3155 v |= qemu_get_byte(f);
3159 uint64_t qemu_get_be64(QEMUFile *f)
3162 v = (uint64_t)qemu_get_be32(f) << 32;
3163 v |= qemu_get_be32(f);
3167 int64_t qemu_ftell(QEMUFile *f)
3172 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
3174 if (fseek(f, pos, whence) < 0)
3179 typedef struct SaveStateEntry {
3183 SaveStateHandler *save_state;
3184 LoadStateHandler *load_state;
3186 struct SaveStateEntry *next;
3189 static SaveStateEntry *first_se;
3191 int register_savevm(const char *idstr,
3194 SaveStateHandler *save_state,
3195 LoadStateHandler *load_state,
3198 SaveStateEntry *se, **pse;
3200 se = qemu_malloc(sizeof(SaveStateEntry));
3203 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
3204 se->instance_id = instance_id;
3205 se->version_id = version_id;
3206 se->save_state = save_state;
3207 se->load_state = load_state;
3208 se->opaque = opaque;
3211 /* add at the end of list */
3213 while (*pse != NULL)
3214 pse = &(*pse)->next;
3219 #define QEMU_VM_FILE_MAGIC 0x5145564d
3220 #define QEMU_VM_FILE_VERSION 0x00000001
3222 int qemu_savevm(const char *filename)
3226 int len, len_pos, cur_pos, saved_vm_running, ret;
3228 saved_vm_running = vm_running;
3231 f = fopen(filename, "wb");
3237 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
3238 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
3240 for(se = first_se; se != NULL; se = se->next) {
3242 len = strlen(se->idstr);
3243 qemu_put_byte(f, len);
3244 qemu_put_buffer(f, se->idstr, len);
3246 qemu_put_be32(f, se->instance_id);
3247 qemu_put_be32(f, se->version_id);
3249 /* record size: filled later */
3251 qemu_put_be32(f, 0);
3253 se->save_state(f, se->opaque);
3255 /* fill record size */
3257 len = ftell(f) - len_pos - 4;
3258 fseek(f, len_pos, SEEK_SET);
3259 qemu_put_be32(f, len);
3260 fseek(f, cur_pos, SEEK_SET);
3266 if (saved_vm_running)
3271 static SaveStateEntry *find_se(const char *idstr, int instance_id)
3275 for(se = first_se; se != NULL; se = se->next) {
3276 if (!strcmp(se->idstr, idstr) &&
3277 instance_id == se->instance_id)
3283 int qemu_loadvm(const char *filename)
3287 int len, cur_pos, ret, instance_id, record_len, version_id;
3288 int saved_vm_running;
3292 saved_vm_running = vm_running;
3295 f = fopen(filename, "rb");
3301 v = qemu_get_be32(f);
3302 if (v != QEMU_VM_FILE_MAGIC)
3304 v = qemu_get_be32(f);
3305 if (v != QEMU_VM_FILE_VERSION) {
3312 len = qemu_get_byte(f);
3315 qemu_get_buffer(f, idstr, len);
3317 instance_id = qemu_get_be32(f);
3318 version_id = qemu_get_be32(f);
3319 record_len = qemu_get_be32(f);
3321 printf("idstr=%s instance=0x%x version=%d len=%d\n",
3322 idstr, instance_id, version_id, record_len);
3325 se = find_se(idstr, instance_id);
3327 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
3328 instance_id, idstr);
3330 ret = se->load_state(f, se->opaque, version_id);
3332 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
3333 instance_id, idstr);
3336 /* always seek to exact end of record */
3337 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
3342 if (saved_vm_running)
3347 /***********************************************************/
3348 /* cpu save/restore */
3350 #if defined(TARGET_I386)
3352 static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
3354 qemu_put_be32(f, dt->selector);
3355 qemu_put_betl(f, dt->base);
3356 qemu_put_be32(f, dt->limit);
3357 qemu_put_be32(f, dt->flags);
3360 static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
3362 dt->selector = qemu_get_be32(f);
3363 dt->base = qemu_get_betl(f);
3364 dt->limit = qemu_get_be32(f);
3365 dt->flags = qemu_get_be32(f);
3368 void cpu_save(QEMUFile *f, void *opaque)
3370 CPUState *env = opaque;
3371 uint16_t fptag, fpus, fpuc, fpregs_format;
3375 for(i = 0; i < CPU_NB_REGS; i++)
3376 qemu_put_betls(f, &env->regs[i]);
3377 qemu_put_betls(f, &env->eip);
3378 qemu_put_betls(f, &env->eflags);
3379 hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
3380 qemu_put_be32s(f, &hflags);
3384 fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
3386 for(i = 0; i < 8; i++) {
3387 fptag |= ((!env->fptags[i]) << i);
3390 qemu_put_be16s(f, &fpuc);
3391 qemu_put_be16s(f, &fpus);
3392 qemu_put_be16s(f, &fptag);
3394 #ifdef USE_X86LDOUBLE
3399 qemu_put_be16s(f, &fpregs_format);
3401 for(i = 0; i < 8; i++) {
3402 #ifdef USE_X86LDOUBLE
3406 /* we save the real CPU data (in case of MMX usage only 'mant'
3407 contains the MMX register */
3408 cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
3409 qemu_put_be64(f, mant);
3410 qemu_put_be16(f, exp);
3413 /* if we use doubles for float emulation, we save the doubles to
3414 avoid losing information in case of MMX usage. It can give
3415 problems if the image is restored on a CPU where long
3416 doubles are used instead. */
3417 qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
3421 for(i = 0; i < 6; i++)
3422 cpu_put_seg(f, &env->segs[i]);
3423 cpu_put_seg(f, &env->ldt);
3424 cpu_put_seg(f, &env->tr);
3425 cpu_put_seg(f, &env->gdt);
3426 cpu_put_seg(f, &env->idt);
3428 qemu_put_be32s(f, &env->sysenter_cs);
3429 qemu_put_be32s(f, &env->sysenter_esp);
3430 qemu_put_be32s(f, &env->sysenter_eip);
3432 qemu_put_betls(f, &env->cr[0]);
3433 qemu_put_betls(f, &env->cr[2]);
3434 qemu_put_betls(f, &env->cr[3]);
3435 qemu_put_betls(f, &env->cr[4]);
3437 for(i = 0; i < 8; i++)
3438 qemu_put_betls(f, &env->dr[i]);
3441 qemu_put_be32s(f, &env->a20_mask);
3444 qemu_put_be32s(f, &env->mxcsr);
3445 for(i = 0; i < CPU_NB_REGS; i++) {
3446 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
3447 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
3450 #ifdef TARGET_X86_64
3451 qemu_put_be64s(f, &env->efer);
3452 qemu_put_be64s(f, &env->star);
3453 qemu_put_be64s(f, &env->lstar);
3454 qemu_put_be64s(f, &env->cstar);
3455 qemu_put_be64s(f, &env->fmask);
3456 qemu_put_be64s(f, &env->kernelgsbase);
3460 #ifdef USE_X86LDOUBLE
3461 /* XXX: add that in a FPU generic layer */
3462 union x86_longdouble {
3467 #define MANTD1(fp) (fp & ((1LL << 52) - 1))
3468 #define EXPBIAS1 1023
3469 #define EXPD1(fp) ((fp >> 52) & 0x7FF)
3470 #define SIGND1(fp) ((fp >> 32) & 0x80000000)
3472 static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
3476 p->mant = (MANTD1(temp) << 11) | (1LL << 63);
3477 /* exponent + sign */
3478 e = EXPD1(temp) - EXPBIAS1 + 16383;
3479 e |= SIGND1(temp) >> 16;
3484 int cpu_load(QEMUFile *f, void *opaque, int version_id)
3486 CPUState *env = opaque;
3489 uint16_t fpus, fpuc, fptag, fpregs_format;
3491 if (version_id != 3)
3493 for(i = 0; i < CPU_NB_REGS; i++)
3494 qemu_get_betls(f, &env->regs[i]);
3495 qemu_get_betls(f, &env->eip);
3496 qemu_get_betls(f, &env->eflags);
3497 qemu_get_be32s(f, &hflags);
3499 qemu_get_be16s(f, &fpuc);
3500 qemu_get_be16s(f, &fpus);
3501 qemu_get_be16s(f, &fptag);
3502 qemu_get_be16s(f, &fpregs_format);
3504 /* NOTE: we cannot always restore the FPU state if the image come
3505 from a host with a different 'USE_X86LDOUBLE' define. We guess
3506 if we are in an MMX state to restore correctly in that case. */
3507 guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
3508 for(i = 0; i < 8; i++) {
3512 switch(fpregs_format) {
3514 mant = qemu_get_be64(f);
3515 exp = qemu_get_be16(f);
3516 #ifdef USE_X86LDOUBLE
3517 env->fpregs[i].d = cpu_set_fp80(mant, exp);
3519 /* difficult case */
3521 env->fpregs[i].mmx.MMX_Q(0) = mant;
3523 env->fpregs[i].d = cpu_set_fp80(mant, exp);
3527 mant = qemu_get_be64(f);
3528 #ifdef USE_X86LDOUBLE
3530 union x86_longdouble *p;
3531 /* difficult case */
3532 p = (void *)&env->fpregs[i];
3537 fp64_to_fp80(p, mant);
3541 env->fpregs[i].mmx.MMX_Q(0) = mant;
3550 /* XXX: restore FPU round state */
3551 env->fpstt = (fpus >> 11) & 7;
3552 env->fpus = fpus & ~0x3800;
3554 for(i = 0; i < 8; i++) {
3555 env->fptags[i] = (fptag >> i) & 1;
3558 for(i = 0; i < 6; i++)
3559 cpu_get_seg(f, &env->segs[i]);
3560 cpu_get_seg(f, &env->ldt);
3561 cpu_get_seg(f, &env->tr);
3562 cpu_get_seg(f, &env->gdt);
3563 cpu_get_seg(f, &env->idt);
3565 qemu_get_be32s(f, &env->sysenter_cs);
3566 qemu_get_be32s(f, &env->sysenter_esp);
3567 qemu_get_be32s(f, &env->sysenter_eip);
3569 qemu_get_betls(f, &env->cr[0]);
3570 qemu_get_betls(f, &env->cr[2]);
3571 qemu_get_betls(f, &env->cr[3]);
3572 qemu_get_betls(f, &env->cr[4]);
3574 for(i = 0; i < 8; i++)
3575 qemu_get_betls(f, &env->dr[i]);
3578 qemu_get_be32s(f, &env->a20_mask);
3580 qemu_get_be32s(f, &env->mxcsr);
3581 for(i = 0; i < CPU_NB_REGS; i++) {
3582 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
3583 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
3586 #ifdef TARGET_X86_64
3587 qemu_get_be64s(f, &env->efer);
3588 qemu_get_be64s(f, &env->star);
3589 qemu_get_be64s(f, &env->lstar);
3590 qemu_get_be64s(f, &env->cstar);
3591 qemu_get_be64s(f, &env->fmask);
3592 qemu_get_be64s(f, &env->kernelgsbase);
3595 /* XXX: compute hflags from scratch, except for CPL and IIF */
3596 env->hflags = hflags;
3601 #elif defined(TARGET_PPC)
3602 void cpu_save(QEMUFile *f, void *opaque)
3606 int cpu_load(QEMUFile *f, void *opaque, int version_id)
3611 #elif defined(TARGET_MIPS)
3612 void cpu_save(QEMUFile *f, void *opaque)
3616 int cpu_load(QEMUFile *f, void *opaque, int version_id)
3621 #elif defined(TARGET_SPARC)
3622 void cpu_save(QEMUFile *f, void *opaque)
3624 CPUState *env = opaque;
3628 for(i = 0; i < 8; i++)
3629 qemu_put_betls(f, &env->gregs[i]);
3630 for(i = 0; i < NWINDOWS * 16; i++)
3631 qemu_put_betls(f, &env->regbase[i]);
3634 for(i = 0; i < TARGET_FPREGS; i++) {
3640 qemu_put_betl(f, u.i);
3643 qemu_put_betls(f, &env->pc);
3644 qemu_put_betls(f, &env->npc);
3645 qemu_put_betls(f, &env->y);
3647 qemu_put_be32(f, tmp);
3648 qemu_put_betls(f, &env->fsr);
3649 qemu_put_betls(f, &env->tbr);
3650 #ifndef TARGET_SPARC64
3651 qemu_put_be32s(f, &env->wim);
3653 for(i = 0; i < 16; i++)
3654 qemu_put_be32s(f, &env->mmuregs[i]);
3658 int cpu_load(QEMUFile *f, void *opaque, int version_id)
3660 CPUState *env = opaque;
3664 for(i = 0; i < 8; i++)
3665 qemu_get_betls(f, &env->gregs[i]);
3666 for(i = 0; i < NWINDOWS * 16; i++)
3667 qemu_get_betls(f, &env->regbase[i]);
3670 for(i = 0; i < TARGET_FPREGS; i++) {
3675 u.i = qemu_get_betl(f);
3679 qemu_get_betls(f, &env->pc);
3680 qemu_get_betls(f, &env->npc);
3681 qemu_get_betls(f, &env->y);
3682 tmp = qemu_get_be32(f);
3683 env->cwp = 0; /* needed to ensure that the wrapping registers are
3684 correctly updated */
3686 qemu_get_betls(f, &env->fsr);
3687 qemu_get_betls(f, &env->tbr);
3688 #ifndef TARGET_SPARC64
3689 qemu_get_be32s(f, &env->wim);
3691 for(i = 0; i < 16; i++)
3692 qemu_get_be32s(f, &env->mmuregs[i]);
3698 #elif defined(TARGET_ARM)
3700 /* ??? Need to implement these. */
3701 void cpu_save(QEMUFile *f, void *opaque)
3705 int cpu_load(QEMUFile *f, void *opaque, int version_id)
3712 #warning No CPU save/restore functions
3716 /***********************************************************/
3717 /* ram save/restore */
3719 /* we just avoid storing empty pages */
3720 static void ram_put_page(QEMUFile *f, const uint8_t *buf, int len)
3725 for(i = 1; i < len; i++) {
3729 qemu_put_byte(f, 1);
3730 qemu_put_byte(f, v);
3733 qemu_put_byte(f, 0);
3734 qemu_put_buffer(f, buf, len);
3737 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
3741 v = qemu_get_byte(f);
3744 if (qemu_get_buffer(f, buf, len) != len)
3748 v = qemu_get_byte(f);
3749 memset(buf, v, len);
3757 static void ram_save(QEMUFile *f, void *opaque)
3760 qemu_put_be32(f, phys_ram_size);
3761 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
3762 ram_put_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
3766 static int ram_load(QEMUFile *f, void *opaque, int version_id)
3770 if (version_id != 1)
3772 if (qemu_get_be32(f) != phys_ram_size)
3774 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
3775 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
3782 /***********************************************************/
3783 /* machine registration */
3785 QEMUMachine *first_machine = NULL;
3787 int qemu_register_machine(QEMUMachine *m)
3790 pm = &first_machine;
3798 QEMUMachine *find_machine(const char *name)
3802 for(m = first_machine; m != NULL; m = m->next) {
3803 if (!strcmp(m->name, name))
3809 /***********************************************************/
3810 /* main execution loop */
3812 void gui_update(void *opaque)
3814 display_state.dpy_refresh(&display_state);
3815 qemu_mod_timer(gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
3818 struct vm_change_state_entry {
3819 VMChangeStateHandler *cb;
3821 LIST_ENTRY (vm_change_state_entry) entries;
3824 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3826 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3829 VMChangeStateEntry *e;
3831 e = qemu_mallocz(sizeof (*e));
3837 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3841 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3843 LIST_REMOVE (e, entries);
3847 static void vm_state_notify(int running)
3849 VMChangeStateEntry *e;
3851 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3852 e->cb(e->opaque, running);
3856 /* XXX: support several handlers */
3857 static VMStopHandler *vm_stop_cb;
3858 static void *vm_stop_opaque;
3860 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
3863 vm_stop_opaque = opaque;
3867 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
3881 void vm_stop(int reason)
3884 cpu_disable_ticks();
3888 vm_stop_cb(vm_stop_opaque, reason);
3895 /* reset/shutdown handler */
3897 typedef struct QEMUResetEntry {
3898 QEMUResetHandler *func;
3900 struct QEMUResetEntry *next;
3903 static QEMUResetEntry *first_reset_entry;
3904 static int reset_requested;
3905 static int shutdown_requested;
3906 static int powerdown_requested;
3908 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
3910 QEMUResetEntry **pre, *re;
3912 pre = &first_reset_entry;
3913 while (*pre != NULL)
3914 pre = &(*pre)->next;
3915 re = qemu_mallocz(sizeof(QEMUResetEntry));
3917 re->opaque = opaque;
3922 void qemu_system_reset(void)
3926 /* reset all devices */
3927 for(re = first_reset_entry; re != NULL; re = re->next) {
3928 re->func(re->opaque);
3932 void qemu_system_reset_request(void)
3934 reset_requested = 1;
3936 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
3939 void qemu_system_shutdown_request(void)
3941 shutdown_requested = 1;
3943 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
3946 void qemu_system_powerdown_request(void)
3948 powerdown_requested = 1;
3950 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
3953 void main_loop_wait(int timeout)
3955 IOHandlerRecord *ioh, *ioh_next;
3961 /* XXX: see how to merge it with the select. The constraint is
3962 that the select must be interrupted by the timer */
3966 /* poll any events */
3967 /* XXX: separate device handlers from system ones */
3971 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3973 (!ioh->fd_read_poll ||
3974 ioh->fd_read_poll(ioh->opaque) != 0)) {
3975 FD_SET(ioh->fd, &rfds);
3979 if (ioh->fd_write) {
3980 FD_SET(ioh->fd, &wfds);
3990 tv.tv_usec = timeout * 1000;
3992 ret = select(nfds + 1, &rfds, &wfds, NULL, &tv);
3994 /* XXX: better handling of removal */
3995 for(ioh = first_io_handler; ioh != NULL; ioh = ioh_next) {
3996 ioh_next = ioh->next;
3997 if (FD_ISSET(ioh->fd, &rfds)) {
3998 ioh->fd_read(ioh->opaque);
4000 if (FD_ISSET(ioh->fd, &wfds)) {
4001 ioh->fd_write(ioh->opaque);
4009 #if defined(CONFIG_SLIRP)
4010 /* XXX: merge with the previous select() */
4012 fd_set rfds, wfds, xfds;
4020 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
4023 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
4025 slirp_select_poll(&rfds, &wfds, &xfds);
4031 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
4032 qemu_get_clock(vm_clock));
4033 /* run dma transfers, if any */
4037 /* real time timers */
4038 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
4039 qemu_get_clock(rt_clock));
4042 static CPUState *cur_cpu;
4047 #ifdef CONFIG_PROFILER
4052 cur_cpu = first_cpu;
4059 env = env->next_cpu;
4062 #ifdef CONFIG_PROFILER
4063 ti = profile_getclock();
4065 ret = cpu_exec(env);
4066 #ifdef CONFIG_PROFILER
4067 qemu_time += profile_getclock() - ti;
4069 if (ret != EXCP_HALTED)
4071 /* all CPUs are halted ? */
4072 if (env == cur_cpu) {
4079 if (shutdown_requested) {
4080 ret = EXCP_INTERRUPT;
4083 if (reset_requested) {
4084 reset_requested = 0;
4085 qemu_system_reset();
4086 ret = EXCP_INTERRUPT;
4088 if (powerdown_requested) {
4089 powerdown_requested = 0;
4090 qemu_system_powerdown();
4091 ret = EXCP_INTERRUPT;
4093 if (ret == EXCP_DEBUG) {
4094 vm_stop(EXCP_DEBUG);
4096 /* if hlt instruction, we wait until the next IRQ */
4097 /* XXX: use timeout computed from timers */
4098 if (ret == EXCP_HLT)
4105 #ifdef CONFIG_PROFILER
4106 ti = profile_getclock();
4108 main_loop_wait(timeout);
4109 #ifdef CONFIG_PROFILER
4110 dev_time += profile_getclock() - ti;
4113 cpu_disable_ticks();
4119 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2005 Fabrice Bellard\n"
4120 "usage: %s [options] [disk_image]\n"
4122 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4124 "Standard options:\n"
4125 "-M machine select emulated machine (-M ? for list)\n"
4126 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
4127 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
4128 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
4129 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
4130 "-boot [a|c|d] boot on floppy (a), hard disk (c) or CD-ROM (d)\n"
4131 "-snapshot write to temporary files instead of disk image files\n"
4132 "-m megs set virtual RAM size to megs MB [default=%d]\n"
4133 "-smp n set the number of CPUs to 'n' [default=1]\n"
4134 "-nographic disable graphical output and redirect serial I/Os to console\n"
4136 "-k language use keyboard layout (for example \"fr\" for French)\n"
4139 "-audio-help print list of audio drivers and their options\n"
4140 "-soundhw c1,... enable audio support\n"
4141 " and only specified sound cards (comma separated list)\n"
4142 " use -soundhw ? to get the list of supported cards\n"
4143 " use -soundhw all to enable all of them\n"
4145 "-localtime set the real time clock to local time [default=utc]\n"
4146 "-full-screen start in full screen\n"
4148 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
4150 "-usb enable the USB driver (will be the default soon)\n"
4151 "-usbdevice name add the host or guest USB device 'name'\n"
4152 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
4153 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
4156 "Network options:\n"
4157 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
4158 " create a new Network Interface Card and connect it to VLAN 'n'\n"
4160 "-net user[,vlan=n]\n"
4161 " connect the user mode network stack to VLAN 'n'\n"
4164 "-net tap[,vlan=n],ifname=name\n"
4165 " connect the host TAP network interface to VLAN 'n'\n"
4167 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file]\n"
4168 " connect the host TAP network interface to VLAN 'n' and use\n"
4169 " the network script 'file' (default=%s);\n"
4170 " use 'fd=h' to connect to an already opened TAP interface\n"
4172 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
4173 " connect the vlan 'n' to another VLAN using a socket connection\n"
4174 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
4175 " connect the vlan 'n' to multicast maddr and port\n"
4176 "-net none use it alone to have zero network devices; if no -net option\n"
4177 " is provided, the default is '-net nic -net user'\n"
4180 "-tftp prefix allow tftp access to files starting with prefix [-net user]\n"
4182 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
4184 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
4185 " redirect TCP or UDP connections from host to guest [-net user]\n"
4188 "Linux boot specific:\n"
4189 "-kernel bzImage use 'bzImage' as kernel image\n"
4190 "-append cmdline use 'cmdline' as kernel command line\n"
4191 "-initrd file use 'file' as initial ram disk\n"
4193 "Debug/Expert options:\n"
4194 "-monitor dev redirect the monitor to char device 'dev'\n"
4195 "-serial dev redirect the serial port to char device 'dev'\n"
4196 "-parallel dev redirect the parallel port to char device 'dev'\n"
4197 "-pidfile file Write PID to 'file'\n"
4198 "-S freeze CPU at startup (use 'c' to start execution)\n"
4199 "-s wait gdb connection to port %d\n"
4200 "-p port change gdb connection port\n"
4201 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
4202 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
4203 " translation (t=none or lba) (usually qemu can guess them)\n"
4204 "-L path set the directory for the BIOS and VGA BIOS\n"
4206 "-no-kqemu disable KQEMU kernel module usage\n"
4208 #ifdef USE_CODE_COPY
4209 "-no-code-copy disable code copy acceleration\n"
4212 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
4213 " (default is CL-GD5446 PCI VGA)\n"
4215 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
4217 "During emulation, the following keys are useful:\n"
4218 "ctrl-alt-f toggle full screen\n"
4219 "ctrl-alt-n switch to virtual console 'n'\n"
4220 "ctrl-alt toggle mouse and keyboard grab\n"
4222 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4224 #ifdef CONFIG_SOFTMMU
4231 DEFAULT_NETWORK_SCRIPT,
4233 DEFAULT_GDBSTUB_PORT,
4235 #ifndef CONFIG_SOFTMMU
4237 "NOTE: this version of QEMU is faster but it needs slightly patched OSes to\n"
4238 "work. Please use the 'qemu' executable to have a more accurate (but slower)\n"
4244 #define HAS_ARG 0x0001
4258 QEMU_OPTION_snapshot,
4260 QEMU_OPTION_nographic,
4262 QEMU_OPTION_audio_help,
4263 QEMU_OPTION_soundhw,
4281 QEMU_OPTION_no_code_copy,
4283 QEMU_OPTION_localtime,
4284 QEMU_OPTION_cirrusvga,
4286 QEMU_OPTION_std_vga,
4287 QEMU_OPTION_monitor,
4289 QEMU_OPTION_parallel,
4291 QEMU_OPTION_full_screen,
4292 QEMU_OPTION_pidfile,
4293 QEMU_OPTION_no_kqemu,
4294 QEMU_OPTION_kernel_kqemu,
4295 QEMU_OPTION_win2k_hack,
4297 QEMU_OPTION_usbdevice,
4301 typedef struct QEMUOption {
4307 const QEMUOption qemu_options[] = {
4308 { "h", 0, QEMU_OPTION_h },
4310 { "M", HAS_ARG, QEMU_OPTION_M },
4311 { "fda", HAS_ARG, QEMU_OPTION_fda },
4312 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
4313 { "hda", HAS_ARG, QEMU_OPTION_hda },
4314 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
4315 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
4316 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
4317 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
4318 { "boot", HAS_ARG, QEMU_OPTION_boot },
4319 { "snapshot", 0, QEMU_OPTION_snapshot },
4320 { "m", HAS_ARG, QEMU_OPTION_m },
4321 { "nographic", 0, QEMU_OPTION_nographic },
4322 { "k", HAS_ARG, QEMU_OPTION_k },
4324 { "audio-help", 0, QEMU_OPTION_audio_help },
4325 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
4328 { "net", HAS_ARG, QEMU_OPTION_net},
4330 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
4332 { "smb", HAS_ARG, QEMU_OPTION_smb },
4334 { "redir", HAS_ARG, QEMU_OPTION_redir },
4337 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
4338 { "append", HAS_ARG, QEMU_OPTION_append },
4339 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
4341 { "S", 0, QEMU_OPTION_S },
4342 { "s", 0, QEMU_OPTION_s },
4343 { "p", HAS_ARG, QEMU_OPTION_p },
4344 { "d", HAS_ARG, QEMU_OPTION_d },
4345 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
4346 { "L", HAS_ARG, QEMU_OPTION_L },
4347 { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
4349 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
4350 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
4352 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
4353 { "g", 1, QEMU_OPTION_g },
4355 { "localtime", 0, QEMU_OPTION_localtime },
4356 { "std-vga", 0, QEMU_OPTION_std_vga },
4357 { "monitor", 1, QEMU_OPTION_monitor },
4358 { "serial", 1, QEMU_OPTION_serial },
4359 { "parallel", 1, QEMU_OPTION_parallel },
4360 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
4361 { "full-screen", 0, QEMU_OPTION_full_screen },
4362 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
4363 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
4364 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
4365 { "smp", HAS_ARG, QEMU_OPTION_smp },
4367 /* temporary options */
4368 { "usb", 0, QEMU_OPTION_usb },
4369 { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
4373 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
4375 /* this stack is only used during signal handling */
4376 #define SIGNAL_STACK_SIZE 32768
4378 static uint8_t *signal_stack;
4382 /* password input */
4384 static BlockDriverState *get_bdrv(int index)
4386 BlockDriverState *bs;
4389 bs = bs_table[index];
4390 } else if (index < 6) {
4391 bs = fd_table[index - 4];
4398 static void read_passwords(void)
4400 BlockDriverState *bs;
4404 for(i = 0; i < 6; i++) {
4406 if (bs && bdrv_is_encrypted(bs)) {
4407 term_printf("%s is encrypted.\n", bdrv_get_device_name(bs));
4408 for(j = 0; j < 3; j++) {
4409 monitor_readline("Password: ",
4410 1, password, sizeof(password));
4411 if (bdrv_set_key(bs, password) == 0)
4413 term_printf("invalid password\n");
4419 /* XXX: currently we cannot use simultaneously different CPUs */
4420 void register_machines(void)
4422 #if defined(TARGET_I386)
4423 qemu_register_machine(&pc_machine);
4424 qemu_register_machine(&isapc_machine);
4425 #elif defined(TARGET_PPC)
4426 qemu_register_machine(&heathrow_machine);
4427 qemu_register_machine(&core99_machine);
4428 qemu_register_machine(&prep_machine);
4429 #elif defined(TARGET_MIPS)
4430 qemu_register_machine(&mips_machine);
4431 #elif defined(TARGET_SPARC)
4432 #ifdef TARGET_SPARC64
4433 qemu_register_machine(&sun4u_machine);
4435 qemu_register_machine(&sun4m_machine);
4437 #elif defined(TARGET_ARM)
4438 qemu_register_machine(&integratorcp_machine);
4440 #error unsupported CPU
4445 struct soundhw soundhw[] = {
4448 "Creative Sound Blaster 16",
4451 { .init_isa = SB16_init }
4458 "Yamaha YMF262 (OPL3)",
4460 "Yamaha YM3812 (OPL2)",
4464 { .init_isa = Adlib_init }
4471 "Gravis Ultrasound GF1",
4474 { .init_isa = GUS_init }
4480 "ENSONIQ AudioPCI ES1370",
4483 { .init_pci = es1370_init }
4486 { NULL, NULL, 0, 0, { NULL } }
4489 static void select_soundhw (const char *optarg)
4493 if (*optarg == '?') {
4496 printf ("Valid sound card names (comma separated):\n");
4497 for (c = soundhw; c->name; ++c) {
4498 printf ("%-11s %s\n", c->name, c->descr);
4500 printf ("\n-soundhw all will enable all of the above\n");
4501 exit (*optarg != '?');
4509 if (!strcmp (optarg, "all")) {
4510 for (c = soundhw; c->name; ++c) {
4518 e = strchr (p, ',');
4519 l = !e ? strlen (p) : (size_t) (e - p);
4521 for (c = soundhw; c->name; ++c) {
4522 if (!strncmp (c->name, p, l)) {
4531 "Unknown sound card name (too big to show)\n");
4534 fprintf (stderr, "Unknown sound card name `%.*s'\n",
4539 p += l + (e != NULL);
4543 goto show_valid_cards;
4548 #define MAX_NET_CLIENTS 32
4550 int main(int argc, char **argv)
4552 #ifdef CONFIG_GDBSTUB
4553 int use_gdbstub, gdbstub_port;
4556 int snapshot, linux_boot;
4557 const char *initrd_filename;
4558 const char *hd_filename[MAX_DISKS], *fd_filename[MAX_FD];
4559 const char *kernel_filename, *kernel_cmdline;
4560 DisplayState *ds = &display_state;
4561 int cyls, heads, secs, translation;
4562 int start_emulation = 1;
4563 char net_clients[MAX_NET_CLIENTS][256];
4566 const char *r, *optarg;
4567 CharDriverState *monitor_hd;
4568 char monitor_device[128];
4569 char serial_devices[MAX_SERIAL_PORTS][128];
4570 int serial_device_index;
4571 char parallel_devices[MAX_PARALLEL_PORTS][128];
4572 int parallel_device_index;
4573 const char *loadvm = NULL;
4574 QEMUMachine *machine;
4575 char usb_devices[MAX_VM_USB_PORTS][128];
4576 int usb_devices_index;
4578 LIST_INIT (&vm_change_state_head);
4579 #if !defined(CONFIG_SOFTMMU)
4580 /* we never want that malloc() uses mmap() */
4581 mallopt(M_MMAP_THRESHOLD, 4096 * 1024);
4583 register_machines();
4584 machine = first_machine;
4585 initrd_filename = NULL;
4586 for(i = 0; i < MAX_FD; i++)
4587 fd_filename[i] = NULL;
4588 for(i = 0; i < MAX_DISKS; i++)
4589 hd_filename[i] = NULL;
4590 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
4591 vga_ram_size = VGA_RAM_SIZE;
4592 bios_size = BIOS_SIZE;
4593 #ifdef CONFIG_GDBSTUB
4595 gdbstub_port = DEFAULT_GDBSTUB_PORT;
4599 kernel_filename = NULL;
4600 kernel_cmdline = "";
4606 cyls = heads = secs = 0;
4607 translation = BIOS_ATA_TRANSLATION_AUTO;
4608 pstrcpy(monitor_device, sizeof(monitor_device), "vc");
4610 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
4611 for(i = 1; i < MAX_SERIAL_PORTS; i++)
4612 serial_devices[i][0] = '\0';
4613 serial_device_index = 0;
4615 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
4616 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
4617 parallel_devices[i][0] = '\0';
4618 parallel_device_index = 0;
4620 usb_devices_index = 0;
4625 /* default mac address of the first network interface */
4633 hd_filename[0] = argv[optind++];
4635 const QEMUOption *popt;
4638 popt = qemu_options;
4641 fprintf(stderr, "%s: invalid option -- '%s'\n",
4645 if (!strcmp(popt->name, r + 1))
4649 if (popt->flags & HAS_ARG) {
4650 if (optind >= argc) {
4651 fprintf(stderr, "%s: option '%s' requires an argument\n",
4655 optarg = argv[optind++];
4660 switch(popt->index) {
4662 machine = find_machine(optarg);
4665 printf("Supported machines are:\n");
4666 for(m = first_machine; m != NULL; m = m->next) {
4667 printf("%-10s %s%s\n",
4669 m == first_machine ? " (default)" : "");
4674 case QEMU_OPTION_initrd:
4675 initrd_filename = optarg;
4677 case QEMU_OPTION_hda:
4678 case QEMU_OPTION_hdb:
4679 case QEMU_OPTION_hdc:
4680 case QEMU_OPTION_hdd:
4683 hd_index = popt->index - QEMU_OPTION_hda;
4684 hd_filename[hd_index] = optarg;
4685 if (hd_index == cdrom_index)
4689 case QEMU_OPTION_snapshot:
4692 case QEMU_OPTION_hdachs:
4696 cyls = strtol(p, (char **)&p, 0);
4697 if (cyls < 1 || cyls > 16383)
4702 heads = strtol(p, (char **)&p, 0);
4703 if (heads < 1 || heads > 16)
4708 secs = strtol(p, (char **)&p, 0);
4709 if (secs < 1 || secs > 63)
4713 if (!strcmp(p, "none"))
4714 translation = BIOS_ATA_TRANSLATION_NONE;
4715 else if (!strcmp(p, "lba"))
4716 translation = BIOS_ATA_TRANSLATION_LBA;
4717 else if (!strcmp(p, "auto"))
4718 translation = BIOS_ATA_TRANSLATION_AUTO;
4721 } else if (*p != '\0') {
4723 fprintf(stderr, "qemu: invalid physical CHS format\n");
4728 case QEMU_OPTION_nographic:
4729 pstrcpy(monitor_device, sizeof(monitor_device), "stdio");
4730 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "stdio");
4733 case QEMU_OPTION_kernel:
4734 kernel_filename = optarg;
4736 case QEMU_OPTION_append:
4737 kernel_cmdline = optarg;
4739 case QEMU_OPTION_cdrom:
4740 if (cdrom_index >= 0) {
4741 hd_filename[cdrom_index] = optarg;
4744 case QEMU_OPTION_boot:
4745 boot_device = optarg[0];
4746 if (boot_device != 'a' &&
4749 boot_device != 'n' &&
4751 boot_device != 'c' && boot_device != 'd') {
4752 fprintf(stderr, "qemu: invalid boot device '%c'\n", boot_device);
4756 case QEMU_OPTION_fda:
4757 fd_filename[0] = optarg;
4759 case QEMU_OPTION_fdb:
4760 fd_filename[1] = optarg;
4762 case QEMU_OPTION_no_code_copy:
4763 code_copy_enabled = 0;
4765 case QEMU_OPTION_net:
4766 if (nb_net_clients >= MAX_NET_CLIENTS) {
4767 fprintf(stderr, "qemu: too many network clients\n");
4770 pstrcpy(net_clients[nb_net_clients],
4771 sizeof(net_clients[0]),
4776 case QEMU_OPTION_tftp:
4777 tftp_prefix = optarg;
4780 case QEMU_OPTION_smb:
4781 net_slirp_smb(optarg);
4784 case QEMU_OPTION_redir:
4785 net_slirp_redir(optarg);
4789 case QEMU_OPTION_audio_help:
4793 case QEMU_OPTION_soundhw:
4794 select_soundhw (optarg);
4801 ram_size = atoi(optarg) * 1024 * 1024;
4804 if (ram_size > PHYS_RAM_MAX_SIZE) {
4805 fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
4806 PHYS_RAM_MAX_SIZE / (1024 * 1024));
4815 mask = cpu_str_to_log_mask(optarg);
4817 printf("Log items (comma separated):\n");
4818 for(item = cpu_log_items; item->mask != 0; item++) {
4819 printf("%-10s %s\n", item->name, item->help);
4826 #ifdef CONFIG_GDBSTUB
4831 gdbstub_port = atoi(optarg);
4838 start_emulation = 0;
4841 keyboard_layout = optarg;
4843 case QEMU_OPTION_localtime:
4846 case QEMU_OPTION_cirrusvga:
4847 cirrus_vga_enabled = 1;
4849 case QEMU_OPTION_std_vga:
4850 cirrus_vga_enabled = 0;
4857 w = strtol(p, (char **)&p, 10);
4860 fprintf(stderr, "qemu: invalid resolution or depth\n");
4866 h = strtol(p, (char **)&p, 10);
4871 depth = strtol(p, (char **)&p, 10);
4872 if (depth != 8 && depth != 15 && depth != 16 &&
4873 depth != 24 && depth != 32)
4875 } else if (*p == '\0') {
4876 depth = graphic_depth;
4883 graphic_depth = depth;
4886 case QEMU_OPTION_monitor:
4887 pstrcpy(monitor_device, sizeof(monitor_device), optarg);
4889 case QEMU_OPTION_serial:
4890 if (serial_device_index >= MAX_SERIAL_PORTS) {
4891 fprintf(stderr, "qemu: too many serial ports\n");
4894 pstrcpy(serial_devices[serial_device_index],
4895 sizeof(serial_devices[0]), optarg);
4896 serial_device_index++;
4898 case QEMU_OPTION_parallel:
4899 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
4900 fprintf(stderr, "qemu: too many parallel ports\n");
4903 pstrcpy(parallel_devices[parallel_device_index],
4904 sizeof(parallel_devices[0]), optarg);
4905 parallel_device_index++;
4907 case QEMU_OPTION_loadvm:
4910 case QEMU_OPTION_full_screen:
4913 case QEMU_OPTION_pidfile:
4914 create_pidfile(optarg);
4917 case QEMU_OPTION_win2k_hack:
4918 win2k_install_hack = 1;
4922 case QEMU_OPTION_no_kqemu:
4925 case QEMU_OPTION_kernel_kqemu:
4929 case QEMU_OPTION_usb:
4932 case QEMU_OPTION_usbdevice:
4934 if (usb_devices_index >= MAX_VM_USB_PORTS) {
4935 fprintf(stderr, "Too many USB devices\n");
4938 pstrcpy(usb_devices[usb_devices_index],
4939 sizeof(usb_devices[usb_devices_index]),
4941 usb_devices_index++;
4943 case QEMU_OPTION_smp:
4944 smp_cpus = atoi(optarg);
4945 if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
4946 fprintf(stderr, "Invalid number of CPUs\n");
4958 linux_boot = (kernel_filename != NULL);
4961 hd_filename[0] == '\0' &&
4962 (cdrom_index >= 0 && hd_filename[cdrom_index] == '\0') &&
4963 fd_filename[0] == '\0')
4966 /* boot to cd by default if no hard disk */
4967 if (hd_filename[0] == '\0' && boot_device == 'c') {
4968 if (fd_filename[0] != '\0')
4974 #if !defined(CONFIG_SOFTMMU)
4975 /* must avoid mmap() usage of glibc by setting a buffer "by hand" */
4977 static uint8_t stdout_buf[4096];
4978 setvbuf(stdout, stdout_buf, _IOLBF, sizeof(stdout_buf));
4981 setvbuf(stdout, NULL, _IOLBF, 0);
4988 /* init network clients */
4989 if (nb_net_clients == 0) {
4990 /* if no clients, we use a default config */
4991 pstrcpy(net_clients[0], sizeof(net_clients[0]),
4993 pstrcpy(net_clients[1], sizeof(net_clients[0]),
4998 for(i = 0;i < nb_net_clients; i++) {
4999 if (net_client_init(net_clients[i]) < 0)
5003 /* init the memory */
5004 phys_ram_size = ram_size + vga_ram_size + bios_size;
5006 #ifdef CONFIG_SOFTMMU
5007 phys_ram_base = qemu_vmalloc(phys_ram_size);
5008 if (!phys_ram_base) {
5009 fprintf(stderr, "Could not allocate physical memory\n");
5013 /* as we must map the same page at several addresses, we must use
5018 tmpdir = getenv("QEMU_TMPDIR");
5021 snprintf(phys_ram_file, sizeof(phys_ram_file), "%s/vlXXXXXX", tmpdir);
5022 if (mkstemp(phys_ram_file) < 0) {
5023 fprintf(stderr, "Could not create temporary memory file '%s'\n",
5027 phys_ram_fd = open(phys_ram_file, O_CREAT | O_TRUNC | O_RDWR, 0600);
5028 if (phys_ram_fd < 0) {
5029 fprintf(stderr, "Could not open temporary memory file '%s'\n",
5033 ftruncate(phys_ram_fd, phys_ram_size);
5034 unlink(phys_ram_file);
5035 phys_ram_base = mmap(get_mmap_addr(phys_ram_size),
5037 PROT_WRITE | PROT_READ, MAP_SHARED | MAP_FIXED,
5039 if (phys_ram_base == MAP_FAILED) {
5040 fprintf(stderr, "Could not map physical memory\n");
5046 /* we always create the cdrom drive, even if no disk is there */
5048 if (cdrom_index >= 0) {
5049 bs_table[cdrom_index] = bdrv_new("cdrom");
5050 bdrv_set_type_hint(bs_table[cdrom_index], BDRV_TYPE_CDROM);
5053 /* open the virtual block devices */
5054 for(i = 0; i < MAX_DISKS; i++) {
5055 if (hd_filename[i]) {
5058 snprintf(buf, sizeof(buf), "hd%c", i + 'a');
5059 bs_table[i] = bdrv_new(buf);
5061 if (bdrv_open(bs_table[i], hd_filename[i], snapshot) < 0) {
5062 fprintf(stderr, "qemu: could not open hard disk image '%s'\n",
5066 if (i == 0 && cyls != 0) {
5067 bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
5068 bdrv_set_translation_hint(bs_table[i], translation);
5073 /* we always create at least one floppy disk */
5074 fd_table[0] = bdrv_new("fda");
5075 bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
5077 for(i = 0; i < MAX_FD; i++) {
5078 if (fd_filename[i]) {
5081 snprintf(buf, sizeof(buf), "fd%c", i + 'a');
5082 fd_table[i] = bdrv_new(buf);
5083 bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
5085 if (fd_filename[i] != '\0') {
5086 if (bdrv_open(fd_table[i], fd_filename[i], snapshot) < 0) {
5087 fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
5095 /* init USB devices */
5097 vm_usb_hub = usb_hub_init(vm_usb_ports, MAX_VM_USB_PORTS);
5098 for(i = 0; i < usb_devices_index; i++) {
5099 if (usb_device_add(usb_devices[i]) < 0) {
5100 fprintf(stderr, "Warning: could not add USB device %s\n",
5106 register_savevm("timer", 0, 1, timer_save, timer_load, NULL);
5107 register_savevm("ram", 0, 1, ram_save, ram_load, NULL);
5110 cpu_calibrate_ticks();
5114 dumb_display_init(ds);
5116 #if defined(CONFIG_SDL)
5117 sdl_display_init(ds, full_screen);
5118 #elif defined(CONFIG_COCOA)
5119 cocoa_display_init(ds, full_screen);
5121 dumb_display_init(ds);
5125 vga_console = graphic_console_init(ds);
5127 monitor_hd = qemu_chr_open(monitor_device);
5129 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
5132 monitor_init(monitor_hd, !nographic);
5134 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5135 if (serial_devices[i][0] != '\0') {
5136 serial_hds[i] = qemu_chr_open(serial_devices[i]);
5137 if (!serial_hds[i]) {
5138 fprintf(stderr, "qemu: could not open serial device '%s'\n",
5142 if (!strcmp(serial_devices[i], "vc"))
5143 qemu_chr_printf(serial_hds[i], "serial%d console\n", i);
5147 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5148 if (parallel_devices[i][0] != '\0') {
5149 parallel_hds[i] = qemu_chr_open(parallel_devices[i]);
5150 if (!parallel_hds[i]) {
5151 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
5152 parallel_devices[i]);
5155 if (!strcmp(parallel_devices[i], "vc"))
5156 qemu_chr_printf(parallel_hds[i], "parallel%d console\n", i);
5160 /* setup cpu signal handlers for MMU / self modifying code handling */
5161 #if !defined(CONFIG_SOFTMMU)
5163 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
5166 signal_stack = memalign(16, SIGNAL_STACK_SIZE);
5167 stk.ss_sp = signal_stack;
5168 stk.ss_size = SIGNAL_STACK_SIZE;
5171 if (sigaltstack(&stk, NULL) < 0) {
5172 perror("sigaltstack");
5178 struct sigaction act;
5180 sigfillset(&act.sa_mask);
5181 act.sa_flags = SA_SIGINFO;
5182 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
5183 act.sa_flags |= SA_ONSTACK;
5185 act.sa_sigaction = host_segv_handler;
5186 sigaction(SIGSEGV, &act, NULL);
5187 sigaction(SIGBUS, &act, NULL);
5188 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
5189 sigaction(SIGFPE, &act, NULL);
5196 struct sigaction act;
5197 sigfillset(&act.sa_mask);
5199 act.sa_handler = SIG_IGN;
5200 sigaction(SIGPIPE, &act, NULL);
5205 machine->init(ram_size, vga_ram_size, boot_device,
5206 ds, fd_filename, snapshot,
5207 kernel_filename, kernel_cmdline, initrd_filename);
5209 gui_timer = qemu_new_timer(rt_clock, gui_update, NULL);
5210 qemu_mod_timer(gui_timer, qemu_get_clock(rt_clock));
5212 #ifdef CONFIG_GDBSTUB
5214 if (gdbserver_start(gdbstub_port) < 0) {
5215 fprintf(stderr, "Could not open gdbserver socket on port %d\n",
5219 printf("Waiting gdb connection on port %d\n", gdbstub_port);
5224 qemu_loadvm(loadvm);
5227 /* XXX: simplify init */
5229 if (start_emulation) {