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 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
141 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
143 int win2k_install_hack = 0;
146 USBPort *vm_usb_ports[MAX_VM_USB_PORTS];
147 USBDevice *vm_usb_hub;
148 static VLANState *first_vlan;
150 #if defined(TARGET_SPARC)
152 #elif defined(TARGET_I386)
158 /***********************************************************/
159 /* x86 ISA bus support */
161 target_phys_addr_t isa_mem_base = 0;
164 uint32_t default_ioport_readb(void *opaque, uint32_t address)
166 #ifdef DEBUG_UNUSED_IOPORT
167 fprintf(stderr, "inb: port=0x%04x\n", address);
172 void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
174 #ifdef DEBUG_UNUSED_IOPORT
175 fprintf(stderr, "outb: port=0x%04x data=0x%02x\n", address, data);
179 /* default is to make two byte accesses */
180 uint32_t default_ioport_readw(void *opaque, uint32_t address)
183 data = ioport_read_table[0][address](ioport_opaque[address], address);
184 address = (address + 1) & (MAX_IOPORTS - 1);
185 data |= ioport_read_table[0][address](ioport_opaque[address], address) << 8;
189 void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
191 ioport_write_table[0][address](ioport_opaque[address], address, data & 0xff);
192 address = (address + 1) & (MAX_IOPORTS - 1);
193 ioport_write_table[0][address](ioport_opaque[address], address, (data >> 8) & 0xff);
196 uint32_t default_ioport_readl(void *opaque, uint32_t address)
198 #ifdef DEBUG_UNUSED_IOPORT
199 fprintf(stderr, "inl: port=0x%04x\n", address);
204 void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
206 #ifdef DEBUG_UNUSED_IOPORT
207 fprintf(stderr, "outl: port=0x%04x data=0x%02x\n", address, data);
211 void init_ioports(void)
215 for(i = 0; i < MAX_IOPORTS; i++) {
216 ioport_read_table[0][i] = default_ioport_readb;
217 ioport_write_table[0][i] = default_ioport_writeb;
218 ioport_read_table[1][i] = default_ioport_readw;
219 ioport_write_table[1][i] = default_ioport_writew;
220 ioport_read_table[2][i] = default_ioport_readl;
221 ioport_write_table[2][i] = default_ioport_writel;
225 /* size is the word size in byte */
226 int register_ioport_read(int start, int length, int size,
227 IOPortReadFunc *func, void *opaque)
233 } else if (size == 2) {
235 } else if (size == 4) {
238 hw_error("register_ioport_read: invalid size");
241 for(i = start; i < start + length; i += size) {
242 ioport_read_table[bsize][i] = func;
243 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
244 hw_error("register_ioport_read: invalid opaque");
245 ioport_opaque[i] = opaque;
250 /* size is the word size in byte */
251 int register_ioport_write(int start, int length, int size,
252 IOPortWriteFunc *func, void *opaque)
258 } else if (size == 2) {
260 } else if (size == 4) {
263 hw_error("register_ioport_write: invalid size");
266 for(i = start; i < start + length; i += size) {
267 ioport_write_table[bsize][i] = func;
268 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
269 hw_error("register_ioport_read: invalid opaque");
270 ioport_opaque[i] = opaque;
275 void isa_unassign_ioport(int start, int length)
279 for(i = start; i < start + length; i++) {
280 ioport_read_table[0][i] = default_ioport_readb;
281 ioport_read_table[1][i] = default_ioport_readw;
282 ioport_read_table[2][i] = default_ioport_readl;
284 ioport_write_table[0][i] = default_ioport_writeb;
285 ioport_write_table[1][i] = default_ioport_writew;
286 ioport_write_table[2][i] = default_ioport_writel;
290 /***********************************************************/
292 void pstrcpy(char *buf, int buf_size, const char *str)
302 if (c == 0 || q >= buf + buf_size - 1)
309 /* strcat and truncate. */
310 char *pstrcat(char *buf, int buf_size, const char *s)
315 pstrcpy(buf + len, buf_size - len, s);
319 int strstart(const char *str, const char *val, const char **ptr)
335 /* return the size or -1 if error */
336 int get_image_size(const char *filename)
339 fd = open(filename, O_RDONLY | O_BINARY);
342 size = lseek(fd, 0, SEEK_END);
347 /* return the size or -1 if error */
348 int load_image(const char *filename, uint8_t *addr)
351 fd = open(filename, O_RDONLY | O_BINARY);
354 size = lseek(fd, 0, SEEK_END);
355 lseek(fd, 0, SEEK_SET);
356 if (read(fd, addr, size) != size) {
364 void cpu_outb(CPUState *env, int addr, int val)
367 if (loglevel & CPU_LOG_IOPORT)
368 fprintf(logfile, "outb: %04x %02x\n", addr, val);
370 ioport_write_table[0][addr](ioport_opaque[addr], addr, val);
373 env->last_io_time = cpu_get_time_fast();
377 void cpu_outw(CPUState *env, int addr, int val)
380 if (loglevel & CPU_LOG_IOPORT)
381 fprintf(logfile, "outw: %04x %04x\n", addr, val);
383 ioport_write_table[1][addr](ioport_opaque[addr], addr, val);
386 env->last_io_time = cpu_get_time_fast();
390 void cpu_outl(CPUState *env, int addr, int val)
393 if (loglevel & CPU_LOG_IOPORT)
394 fprintf(logfile, "outl: %04x %08x\n", addr, val);
396 ioport_write_table[2][addr](ioport_opaque[addr], addr, val);
399 env->last_io_time = cpu_get_time_fast();
403 int cpu_inb(CPUState *env, int addr)
406 val = ioport_read_table[0][addr](ioport_opaque[addr], addr);
408 if (loglevel & CPU_LOG_IOPORT)
409 fprintf(logfile, "inb : %04x %02x\n", addr, val);
413 env->last_io_time = cpu_get_time_fast();
418 int cpu_inw(CPUState *env, int addr)
421 val = ioport_read_table[1][addr](ioport_opaque[addr], addr);
423 if (loglevel & CPU_LOG_IOPORT)
424 fprintf(logfile, "inw : %04x %04x\n", addr, val);
428 env->last_io_time = cpu_get_time_fast();
433 int cpu_inl(CPUState *env, int addr)
436 val = ioport_read_table[2][addr](ioport_opaque[addr], addr);
438 if (loglevel & CPU_LOG_IOPORT)
439 fprintf(logfile, "inl : %04x %08x\n", addr, val);
443 env->last_io_time = cpu_get_time_fast();
448 /***********************************************************/
449 void hw_error(const char *fmt, ...)
455 fprintf(stderr, "qemu: hardware error: ");
456 vfprintf(stderr, fmt, ap);
457 fprintf(stderr, "\n");
458 for(env = first_cpu; env != NULL; env = env->next_cpu) {
459 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
461 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
463 cpu_dump_state(env, stderr, fprintf, 0);
470 /***********************************************************/
473 static QEMUPutKBDEvent *qemu_put_kbd_event;
474 static void *qemu_put_kbd_event_opaque;
475 static QEMUPutMouseEvent *qemu_put_mouse_event;
476 static void *qemu_put_mouse_event_opaque;
478 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
480 qemu_put_kbd_event_opaque = opaque;
481 qemu_put_kbd_event = func;
484 void qemu_add_mouse_event_handler(QEMUPutMouseEvent *func, void *opaque)
486 qemu_put_mouse_event_opaque = opaque;
487 qemu_put_mouse_event = func;
490 void kbd_put_keycode(int keycode)
492 if (qemu_put_kbd_event) {
493 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
497 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
499 if (qemu_put_mouse_event) {
500 qemu_put_mouse_event(qemu_put_mouse_event_opaque,
501 dx, dy, dz, buttons_state);
505 /***********************************************************/
508 #if defined(__powerpc__)
510 static inline uint32_t get_tbl(void)
513 asm volatile("mftb %0" : "=r" (tbl));
517 static inline uint32_t get_tbu(void)
520 asm volatile("mftbu %0" : "=r" (tbl));
524 int64_t cpu_get_real_ticks(void)
527 /* NOTE: we test if wrapping has occurred */
533 return ((int64_t)h << 32) | l;
536 #elif defined(__i386__)
538 int64_t cpu_get_real_ticks(void)
541 asm volatile ("rdtsc" : "=A" (val));
545 #elif defined(__x86_64__)
547 int64_t cpu_get_real_ticks(void)
551 asm volatile("rdtsc" : "=a" (low), "=d" (high));
558 #elif defined(__ia64)
560 int64_t cpu_get_real_ticks(void)
563 asm volatile ("mov %0 = ar.itc" : "=r"(val) :: "memory");
567 #elif defined(__s390__)
569 int64_t cpu_get_real_ticks(void)
572 asm volatile("stck 0(%1)" : "=m" (val) : "a" (&val) : "cc");
577 #error unsupported CPU
580 static int64_t cpu_ticks_offset;
581 static int cpu_ticks_enabled;
583 static inline int64_t cpu_get_ticks(void)
585 if (!cpu_ticks_enabled) {
586 return cpu_ticks_offset;
588 return cpu_get_real_ticks() + cpu_ticks_offset;
592 /* enable cpu_get_ticks() */
593 void cpu_enable_ticks(void)
595 if (!cpu_ticks_enabled) {
596 cpu_ticks_offset -= cpu_get_real_ticks();
597 cpu_ticks_enabled = 1;
601 /* disable cpu_get_ticks() : the clock is stopped. You must not call
602 cpu_get_ticks() after that. */
603 void cpu_disable_ticks(void)
605 if (cpu_ticks_enabled) {
606 cpu_ticks_offset = cpu_get_ticks();
607 cpu_ticks_enabled = 0;
611 static int64_t get_clock(void)
616 return ((int64_t)tb.time * 1000 + (int64_t)tb.millitm) * 1000;
619 gettimeofday(&tv, NULL);
620 return tv.tv_sec * 1000000LL + tv.tv_usec;
624 void cpu_calibrate_ticks(void)
629 ticks = cpu_get_real_ticks();
635 usec = get_clock() - usec;
636 ticks = cpu_get_real_ticks() - ticks;
637 ticks_per_sec = (ticks * 1000000LL + (usec >> 1)) / usec;
640 /* compute with 96 bit intermediate result: (a*b)/c */
641 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
646 #ifdef WORDS_BIGENDIAN
656 rl = (uint64_t)u.l.low * (uint64_t)b;
657 rh = (uint64_t)u.l.high * (uint64_t)b;
660 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
664 #define QEMU_TIMER_REALTIME 0
665 #define QEMU_TIMER_VIRTUAL 1
669 /* XXX: add frequency */
677 struct QEMUTimer *next;
683 static QEMUTimer *active_timers[2];
685 static MMRESULT timerID;
687 /* frequency of the times() clock tick */
688 static int timer_freq;
691 QEMUClock *qemu_new_clock(int type)
694 clock = qemu_mallocz(sizeof(QEMUClock));
701 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
705 ts = qemu_mallocz(sizeof(QEMUTimer));
712 void qemu_free_timer(QEMUTimer *ts)
717 /* stop a timer, but do not dealloc it */
718 void qemu_del_timer(QEMUTimer *ts)
722 /* NOTE: this code must be signal safe because
723 qemu_timer_expired() can be called from a signal. */
724 pt = &active_timers[ts->clock->type];
737 /* modify the current timer so that it will be fired when current_time
738 >= expire_time. The corresponding callback will be called. */
739 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
745 /* add the timer in the sorted list */
746 /* NOTE: this code must be signal safe because
747 qemu_timer_expired() can be called from a signal. */
748 pt = &active_timers[ts->clock->type];
753 if (t->expire_time > expire_time)
757 ts->expire_time = expire_time;
762 int qemu_timer_pending(QEMUTimer *ts)
765 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
772 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
776 return (timer_head->expire_time <= current_time);
779 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
785 if (!ts || ts->expire_time > current_time)
787 /* remove timer from the list before calling the callback */
788 *ptimer_head = ts->next;
791 /* run the callback (the timer list can be modified) */
796 int64_t qemu_get_clock(QEMUClock *clock)
798 switch(clock->type) {
799 case QEMU_TIMER_REALTIME:
801 return GetTickCount();
806 /* Note that using gettimeofday() is not a good solution
807 for timers because its value change when the date is
809 if (timer_freq == 100) {
810 return times(&tp) * 10;
812 return ((int64_t)times(&tp) * 1000) / timer_freq;
817 case QEMU_TIMER_VIRTUAL:
818 return cpu_get_ticks();
823 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
825 uint64_t expire_time;
827 if (qemu_timer_pending(ts)) {
828 expire_time = ts->expire_time;
832 qemu_put_be64(f, expire_time);
835 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
837 uint64_t expire_time;
839 expire_time = qemu_get_be64(f);
840 if (expire_time != -1) {
841 qemu_mod_timer(ts, expire_time);
847 static void timer_save(QEMUFile *f, void *opaque)
849 if (cpu_ticks_enabled) {
850 hw_error("cannot save state if virtual timers are running");
852 qemu_put_be64s(f, &cpu_ticks_offset);
853 qemu_put_be64s(f, &ticks_per_sec);
856 static int timer_load(QEMUFile *f, void *opaque, int version_id)
860 if (cpu_ticks_enabled) {
863 qemu_get_be64s(f, &cpu_ticks_offset);
864 qemu_get_be64s(f, &ticks_per_sec);
869 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
870 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
872 static void host_alarm_handler(int host_signum)
876 #define DISP_FREQ 1000
878 static int64_t delta_min = INT64_MAX;
879 static int64_t delta_max, delta_cum, last_clock, delta, ti;
881 ti = qemu_get_clock(vm_clock);
882 if (last_clock != 0) {
883 delta = ti - last_clock;
884 if (delta < delta_min)
886 if (delta > delta_max)
889 if (++count == DISP_FREQ) {
890 printf("timer: min=%lld us max=%lld us avg=%lld us avg_freq=%0.3f Hz\n",
891 muldiv64(delta_min, 1000000, ticks_per_sec),
892 muldiv64(delta_max, 1000000, ticks_per_sec),
893 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
894 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
896 delta_min = INT64_MAX;
904 if (qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
905 qemu_get_clock(vm_clock)) ||
906 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
907 qemu_get_clock(rt_clock))) {
908 CPUState *env = cpu_single_env;
910 /* stop the currently executing cpu because a timer occured */
911 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
913 if (env->kqemu_enabled) {
914 kqemu_cpu_interrupt(env);
923 #if defined(__linux__)
925 #define RTC_FREQ 1024
929 static int start_rtc_timer(void)
931 rtc_fd = open("/dev/rtc", O_RDONLY);
934 if (ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
935 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
936 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
937 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
940 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
945 pit_min_timer_count = PIT_FREQ / RTC_FREQ;
951 static int start_rtc_timer(void)
956 #endif /* !defined(__linux__) */
958 #endif /* !defined(_WIN32) */
960 static void init_timers(void)
962 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
963 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
968 timerID = timeSetEvent(1, // interval (ms)
970 host_alarm_handler, // function
971 (DWORD)&count, // user parameter
972 TIME_PERIODIC | TIME_CALLBACK_FUNCTION);
974 perror("failed timer alarm");
978 pit_min_timer_count = ((uint64_t)10000 * PIT_FREQ) / 1000000;
981 struct sigaction act;
982 struct itimerval itv;
984 /* get times() syscall frequency */
985 timer_freq = sysconf(_SC_CLK_TCK);
988 sigfillset(&act.sa_mask);
990 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
991 act.sa_flags |= SA_ONSTACK;
993 act.sa_handler = host_alarm_handler;
994 sigaction(SIGALRM, &act, NULL);
996 itv.it_interval.tv_sec = 0;
997 itv.it_interval.tv_usec = 999; /* for i386 kernel 2.6 to get 1 ms */
998 itv.it_value.tv_sec = 0;
999 itv.it_value.tv_usec = 10 * 1000;
1000 setitimer(ITIMER_REAL, &itv, NULL);
1001 /* we probe the tick duration of the kernel to inform the user if
1002 the emulated kernel requested a too high timer frequency */
1003 getitimer(ITIMER_REAL, &itv);
1005 #if defined(__linux__)
1006 if (itv.it_interval.tv_usec > 1000) {
1007 /* try to use /dev/rtc to have a faster timer */
1008 if (start_rtc_timer() < 0)
1010 /* disable itimer */
1011 itv.it_interval.tv_sec = 0;
1012 itv.it_interval.tv_usec = 0;
1013 itv.it_value.tv_sec = 0;
1014 itv.it_value.tv_usec = 0;
1015 setitimer(ITIMER_REAL, &itv, NULL);
1018 sigaction(SIGIO, &act, NULL);
1019 fcntl(rtc_fd, F_SETFL, O_ASYNC);
1020 fcntl(rtc_fd, F_SETOWN, getpid());
1022 #endif /* defined(__linux__) */
1025 pit_min_timer_count = ((uint64_t)itv.it_interval.tv_usec *
1026 PIT_FREQ) / 1000000;
1032 void quit_timers(void)
1035 timeKillEvent(timerID);
1039 /***********************************************************/
1040 /* character device */
1042 int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1044 return s->chr_write(s, buf, len);
1047 int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1051 return s->chr_ioctl(s, cmd, arg);
1054 void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1059 vsnprintf(buf, sizeof(buf), fmt, ap);
1060 qemu_chr_write(s, buf, strlen(buf));
1064 void qemu_chr_send_event(CharDriverState *s, int event)
1066 if (s->chr_send_event)
1067 s->chr_send_event(s, event);
1070 void qemu_chr_add_read_handler(CharDriverState *s,
1071 IOCanRWHandler *fd_can_read,
1072 IOReadHandler *fd_read, void *opaque)
1074 s->chr_add_read_handler(s, fd_can_read, fd_read, opaque);
1077 void qemu_chr_add_event_handler(CharDriverState *s, IOEventHandler *chr_event)
1079 s->chr_event = chr_event;
1082 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1087 static void null_chr_add_read_handler(CharDriverState *chr,
1088 IOCanRWHandler *fd_can_read,
1089 IOReadHandler *fd_read, void *opaque)
1093 CharDriverState *qemu_chr_open_null(void)
1095 CharDriverState *chr;
1097 chr = qemu_mallocz(sizeof(CharDriverState));
1100 chr->chr_write = null_chr_write;
1101 chr->chr_add_read_handler = null_chr_add_read_handler;
1107 #define socket_error() WSAGetLastError()
1109 #define EWOULDBLOCK WSAEWOULDBLOCK
1110 #define EINTR WSAEINTR
1111 #define EINPROGRESS WSAEINPROGRESS
1113 static void socket_cleanup(void)
1118 static int socket_init(void)
1123 ret = WSAStartup(MAKEWORD(2,2), &Data);
1125 err = WSAGetLastError();
1126 fprintf(stderr, "WSAStartup: %d\n", err);
1129 atexit(socket_cleanup);
1133 static int send_all(int fd, const uint8_t *buf, int len1)
1139 ret = send(fd, buf, len, 0);
1142 errno = WSAGetLastError();
1143 if (errno != WSAEWOULDBLOCK) {
1146 } else if (ret == 0) {
1156 void socket_set_nonblock(int fd)
1158 unsigned long opt = 1;
1159 ioctlsocket(fd, FIONBIO, &opt);
1164 #define socket_error() errno
1165 #define closesocket(s) close(s)
1167 static int unix_write(int fd, const uint8_t *buf, int len1)
1173 ret = write(fd, buf, len);
1175 if (errno != EINTR && errno != EAGAIN)
1177 } else if (ret == 0) {
1187 static inline int send_all(int fd, const uint8_t *buf, int len1)
1189 return unix_write(fd, buf, len1);
1192 void socket_set_nonblock(int fd)
1194 fcntl(fd, F_SETFL, O_NONBLOCK);
1196 #endif /* !_WIN32 */
1202 IOCanRWHandler *fd_can_read;
1203 IOReadHandler *fd_read;
1208 #define STDIO_MAX_CLIENTS 2
1210 static int stdio_nb_clients;
1211 static CharDriverState *stdio_clients[STDIO_MAX_CLIENTS];
1213 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1215 FDCharDriver *s = chr->opaque;
1216 return unix_write(s->fd_out, buf, len);
1219 static int fd_chr_read_poll(void *opaque)
1221 CharDriverState *chr = opaque;
1222 FDCharDriver *s = chr->opaque;
1224 s->max_size = s->fd_can_read(s->fd_opaque);
1228 static void fd_chr_read(void *opaque)
1230 CharDriverState *chr = opaque;
1231 FDCharDriver *s = chr->opaque;
1236 if (len > s->max_size)
1240 size = read(s->fd_in, buf, len);
1242 s->fd_read(s->fd_opaque, buf, size);
1246 static void fd_chr_add_read_handler(CharDriverState *chr,
1247 IOCanRWHandler *fd_can_read,
1248 IOReadHandler *fd_read, void *opaque)
1250 FDCharDriver *s = chr->opaque;
1252 if (s->fd_in >= 0) {
1253 s->fd_can_read = fd_can_read;
1254 s->fd_read = fd_read;
1255 s->fd_opaque = opaque;
1256 if (nographic && s->fd_in == 0) {
1258 qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
1259 fd_chr_read, NULL, chr);
1264 /* open a character device to a unix fd */
1265 CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
1267 CharDriverState *chr;
1270 chr = qemu_mallocz(sizeof(CharDriverState));
1273 s = qemu_mallocz(sizeof(FDCharDriver));
1281 chr->chr_write = fd_chr_write;
1282 chr->chr_add_read_handler = fd_chr_add_read_handler;
1286 CharDriverState *qemu_chr_open_file_out(const char *file_out)
1290 fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666);
1293 return qemu_chr_open_fd(-1, fd_out);
1296 CharDriverState *qemu_chr_open_pipe(const char *filename)
1300 fd = open(filename, O_RDWR | O_BINARY);
1303 return qemu_chr_open_fd(fd, fd);
1307 /* for STDIO, we handle the case where several clients use it
1310 #define TERM_ESCAPE 0x01 /* ctrl-a is used for escape */
1312 #define TERM_FIFO_MAX_SIZE 1
1314 static int term_got_escape, client_index;
1315 static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
1318 void term_print_help(void)
1321 "C-a h print this help\n"
1322 "C-a x exit emulator\n"
1323 "C-a s save disk data back to file (if -snapshot)\n"
1324 "C-a b send break (magic sysrq)\n"
1325 "C-a c switch between console and monitor\n"
1326 "C-a C-a send C-a\n"
1330 /* called when a char is received */
1331 static void stdio_received_byte(int ch)
1333 if (term_got_escape) {
1334 term_got_escape = 0;
1345 for (i = 0; i < MAX_DISKS; i++) {
1347 bdrv_commit(bs_table[i]);
1352 if (client_index < stdio_nb_clients) {
1353 CharDriverState *chr;
1356 chr = stdio_clients[client_index];
1358 chr->chr_event(s->fd_opaque, CHR_EVENT_BREAK);
1363 if (client_index >= stdio_nb_clients)
1365 if (client_index == 0) {
1366 /* send a new line in the monitor to get the prompt */
1374 } else if (ch == TERM_ESCAPE) {
1375 term_got_escape = 1;
1378 if (client_index < stdio_nb_clients) {
1380 CharDriverState *chr;
1383 chr = stdio_clients[client_index];
1385 if (s->fd_can_read(s->fd_opaque) > 0) {
1387 s->fd_read(s->fd_opaque, buf, 1);
1388 } else if (term_fifo_size == 0) {
1389 term_fifo[term_fifo_size++] = ch;
1395 static int stdio_read_poll(void *opaque)
1397 CharDriverState *chr;
1400 if (client_index < stdio_nb_clients) {
1401 chr = stdio_clients[client_index];
1403 /* try to flush the queue if needed */
1404 if (term_fifo_size != 0 && s->fd_can_read(s->fd_opaque) > 0) {
1405 s->fd_read(s->fd_opaque, term_fifo, 1);
1408 /* see if we can absorb more chars */
1409 if (term_fifo_size == 0)
1418 static void stdio_read(void *opaque)
1423 size = read(0, buf, 1);
1425 stdio_received_byte(buf[0]);
1428 /* init terminal so that we can grab keys */
1429 static struct termios oldtty;
1430 static int old_fd0_flags;
1432 static void term_exit(void)
1434 tcsetattr (0, TCSANOW, &oldtty);
1435 fcntl(0, F_SETFL, old_fd0_flags);
1438 static void term_init(void)
1442 tcgetattr (0, &tty);
1444 old_fd0_flags = fcntl(0, F_GETFL);
1446 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1447 |INLCR|IGNCR|ICRNL|IXON);
1448 tty.c_oflag |= OPOST;
1449 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1450 /* if graphical mode, we allow Ctrl-C handling */
1452 tty.c_lflag &= ~ISIG;
1453 tty.c_cflag &= ~(CSIZE|PARENB);
1456 tty.c_cc[VTIME] = 0;
1458 tcsetattr (0, TCSANOW, &tty);
1462 fcntl(0, F_SETFL, O_NONBLOCK);
1465 CharDriverState *qemu_chr_open_stdio(void)
1467 CharDriverState *chr;
1470 if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
1472 chr = qemu_chr_open_fd(0, 1);
1473 if (stdio_nb_clients == 0)
1474 qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, NULL);
1475 client_index = stdio_nb_clients;
1477 if (stdio_nb_clients != 0)
1479 chr = qemu_chr_open_fd(0, 1);
1481 stdio_clients[stdio_nb_clients++] = chr;
1482 if (stdio_nb_clients == 1) {
1483 /* set the terminal in raw mode */
1489 #if defined(__linux__)
1490 CharDriverState *qemu_chr_open_pty(void)
1493 char slave_name[1024];
1494 int master_fd, slave_fd;
1496 /* Not satisfying */
1497 if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
1501 /* Disabling local echo and line-buffered output */
1502 tcgetattr (master_fd, &tty);
1503 tty.c_lflag &= ~(ECHO|ICANON|ISIG);
1505 tty.c_cc[VTIME] = 0;
1506 tcsetattr (master_fd, TCSAFLUSH, &tty);
1508 fprintf(stderr, "char device redirected to %s\n", slave_name);
1509 return qemu_chr_open_fd(master_fd, master_fd);
1512 static void tty_serial_init(int fd, int speed,
1513 int parity, int data_bits, int stop_bits)
1519 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1520 speed, parity, data_bits, stop_bits);
1522 tcgetattr (fd, &tty);
1564 cfsetispeed(&tty, spd);
1565 cfsetospeed(&tty, spd);
1567 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1568 |INLCR|IGNCR|ICRNL|IXON);
1569 tty.c_oflag |= OPOST;
1570 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1571 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS);
1592 tty.c_cflag |= PARENB;
1595 tty.c_cflag |= PARENB | PARODD;
1599 tcsetattr (fd, TCSANOW, &tty);
1602 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1604 FDCharDriver *s = chr->opaque;
1607 case CHR_IOCTL_SERIAL_SET_PARAMS:
1609 QEMUSerialSetParams *ssp = arg;
1610 tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
1611 ssp->data_bits, ssp->stop_bits);
1614 case CHR_IOCTL_SERIAL_SET_BREAK:
1616 int enable = *(int *)arg;
1618 tcsendbreak(s->fd_in, 1);
1627 CharDriverState *qemu_chr_open_tty(const char *filename)
1629 CharDriverState *chr;
1632 fd = open(filename, O_RDWR | O_NONBLOCK);
1635 fcntl(fd, F_SETFL, O_NONBLOCK);
1636 tty_serial_init(fd, 115200, 'N', 8, 1);
1637 chr = qemu_chr_open_fd(fd, fd);
1640 chr->chr_ioctl = tty_serial_ioctl;
1644 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1646 int fd = (int)chr->opaque;
1650 case CHR_IOCTL_PP_READ_DATA:
1651 if (ioctl(fd, PPRDATA, &b) < 0)
1653 *(uint8_t *)arg = b;
1655 case CHR_IOCTL_PP_WRITE_DATA:
1656 b = *(uint8_t *)arg;
1657 if (ioctl(fd, PPWDATA, &b) < 0)
1660 case CHR_IOCTL_PP_READ_CONTROL:
1661 if (ioctl(fd, PPRCONTROL, &b) < 0)
1663 *(uint8_t *)arg = b;
1665 case CHR_IOCTL_PP_WRITE_CONTROL:
1666 b = *(uint8_t *)arg;
1667 if (ioctl(fd, PPWCONTROL, &b) < 0)
1670 case CHR_IOCTL_PP_READ_STATUS:
1671 if (ioctl(fd, PPRSTATUS, &b) < 0)
1673 *(uint8_t *)arg = b;
1681 CharDriverState *qemu_chr_open_pp(const char *filename)
1683 CharDriverState *chr;
1686 fd = open(filename, O_RDWR);
1690 if (ioctl(fd, PPCLAIM) < 0) {
1695 chr = qemu_mallocz(sizeof(CharDriverState));
1700 chr->opaque = (void *)fd;
1701 chr->chr_write = null_chr_write;
1702 chr->chr_add_read_handler = null_chr_add_read_handler;
1703 chr->chr_ioctl = pp_ioctl;
1708 CharDriverState *qemu_chr_open_pty(void)
1714 #endif /* !defined(_WIN32) */
1718 IOCanRWHandler *fd_can_read;
1719 IOReadHandler *fd_read;
1722 HANDLE hcom, hrecv, hsend;
1723 OVERLAPPED orecv, osend;
1728 #define NSENDBUF 2048
1729 #define NRECVBUF 2048
1730 #define MAXCONNECT 1
1731 #define NTIMEOUT 5000
1733 static int win_chr_poll(void *opaque);
1734 static int win_chr_pipe_poll(void *opaque);
1736 static void win_chr_close2(WinCharState *s)
1739 CloseHandle(s->hsend);
1743 CloseHandle(s->hrecv);
1747 CloseHandle(s->hcom);
1751 qemu_del_polling_cb(win_chr_pipe_poll, s);
1753 qemu_del_polling_cb(win_chr_poll, s);
1756 static void win_chr_close(CharDriverState *chr)
1758 WinCharState *s = chr->opaque;
1762 static int win_chr_init(WinCharState *s, const char *filename)
1765 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
1770 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1772 fprintf(stderr, "Failed CreateEvent\n");
1775 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1777 fprintf(stderr, "Failed CreateEvent\n");
1781 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
1782 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
1783 if (s->hcom == INVALID_HANDLE_VALUE) {
1784 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
1789 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
1790 fprintf(stderr, "Failed SetupComm\n");
1794 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
1795 size = sizeof(COMMCONFIG);
1796 GetDefaultCommConfig(filename, &comcfg, &size);
1797 comcfg.dcb.DCBlength = sizeof(DCB);
1798 CommConfigDialog(filename, NULL, &comcfg);
1800 if (!SetCommState(s->hcom, &comcfg.dcb)) {
1801 fprintf(stderr, "Failed SetCommState\n");
1805 if (!SetCommMask(s->hcom, EV_ERR)) {
1806 fprintf(stderr, "Failed SetCommMask\n");
1810 cto.ReadIntervalTimeout = MAXDWORD;
1811 if (!SetCommTimeouts(s->hcom, &cto)) {
1812 fprintf(stderr, "Failed SetCommTimeouts\n");
1816 if (!ClearCommError(s->hcom, &err, &comstat)) {
1817 fprintf(stderr, "Failed ClearCommError\n");
1820 qemu_add_polling_cb(win_chr_poll, s);
1828 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
1830 WinCharState *s = chr->opaque;
1831 DWORD len, ret, size, err;
1834 ZeroMemory(&s->osend, sizeof(s->osend));
1835 s->osend.hEvent = s->hsend;
1838 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
1840 ret = WriteFile(s->hcom, buf, len, &size, NULL);
1842 err = GetLastError();
1843 if (err == ERROR_IO_PENDING) {
1844 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
1862 static int win_chr_read_poll(WinCharState *s)
1864 s->max_size = s->fd_can_read(s->win_opaque);
1868 static void win_chr_readfile(WinCharState *s)
1874 ZeroMemory(&s->orecv, sizeof(s->orecv));
1875 s->orecv.hEvent = s->hrecv;
1876 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
1878 err = GetLastError();
1879 if (err == ERROR_IO_PENDING) {
1880 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
1885 s->fd_read(s->win_opaque, buf, size);
1889 static void win_chr_read(WinCharState *s)
1891 if (s->len > s->max_size)
1892 s->len = s->max_size;
1896 win_chr_readfile(s);
1899 static int win_chr_poll(void *opaque)
1901 WinCharState *s = opaque;
1905 ClearCommError(s->hcom, &comerr, &status);
1906 if (status.cbInQue > 0) {
1907 s->len = status.cbInQue;
1908 win_chr_read_poll(s);
1915 static void win_chr_add_read_handler(CharDriverState *chr,
1916 IOCanRWHandler *fd_can_read,
1917 IOReadHandler *fd_read, void *opaque)
1919 WinCharState *s = chr->opaque;
1921 s->fd_can_read = fd_can_read;
1922 s->fd_read = fd_read;
1923 s->win_opaque = opaque;
1926 CharDriverState *qemu_chr_open_win(const char *filename)
1928 CharDriverState *chr;
1931 chr = qemu_mallocz(sizeof(CharDriverState));
1934 s = qemu_mallocz(sizeof(WinCharState));
1940 chr->chr_write = win_chr_write;
1941 chr->chr_add_read_handler = win_chr_add_read_handler;
1942 chr->chr_close = win_chr_close;
1944 if (win_chr_init(s, filename) < 0) {
1952 static int win_chr_pipe_poll(void *opaque)
1954 WinCharState *s = opaque;
1957 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
1960 win_chr_read_poll(s);
1967 static int win_chr_pipe_init(WinCharState *s, const char *filename)
1976 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1978 fprintf(stderr, "Failed CreateEvent\n");
1981 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1983 fprintf(stderr, "Failed CreateEvent\n");
1987 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
1988 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
1989 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
1991 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
1992 if (s->hcom == INVALID_HANDLE_VALUE) {
1993 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
1998 ZeroMemory(&ov, sizeof(ov));
1999 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2000 ret = ConnectNamedPipe(s->hcom, &ov);
2002 fprintf(stderr, "Failed ConnectNamedPipe\n");
2006 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2008 fprintf(stderr, "Failed GetOverlappedResult\n");
2010 CloseHandle(ov.hEvent);
2017 CloseHandle(ov.hEvent);
2020 qemu_add_polling_cb(win_chr_pipe_poll, s);
2029 CharDriverState *qemu_chr_open_win_pipe(const char *filename)
2031 CharDriverState *chr;
2034 chr = qemu_mallocz(sizeof(CharDriverState));
2037 s = qemu_mallocz(sizeof(WinCharState));
2043 chr->chr_write = win_chr_write;
2044 chr->chr_add_read_handler = win_chr_add_read_handler;
2045 chr->chr_close = win_chr_close;
2047 if (win_chr_pipe_init(s, filename) < 0) {
2055 CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
2057 CharDriverState *chr;
2060 chr = qemu_mallocz(sizeof(CharDriverState));
2063 s = qemu_mallocz(sizeof(WinCharState));
2070 chr->chr_write = win_chr_write;
2071 chr->chr_add_read_handler = win_chr_add_read_handler;
2075 CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
2079 fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
2080 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2081 if (fd_out == INVALID_HANDLE_VALUE)
2084 return qemu_chr_open_win_file(fd_out);
2088 CharDriverState *qemu_chr_open(const char *filename)
2092 if (!strcmp(filename, "vc")) {
2093 return text_console_init(&display_state);
2094 } else if (!strcmp(filename, "null")) {
2095 return qemu_chr_open_null();
2098 if (strstart(filename, "file:", &p)) {
2099 return qemu_chr_open_file_out(p);
2100 } else if (strstart(filename, "pipe:", &p)) {
2101 return qemu_chr_open_pipe(p);
2102 } else if (!strcmp(filename, "pty")) {
2103 return qemu_chr_open_pty();
2104 } else if (!strcmp(filename, "stdio")) {
2105 return qemu_chr_open_stdio();
2108 #if defined(__linux__)
2109 if (strstart(filename, "/dev/parport", NULL)) {
2110 return qemu_chr_open_pp(filename);
2112 if (strstart(filename, "/dev/", NULL)) {
2113 return qemu_chr_open_tty(filename);
2117 if (strstart(filename, "COM", NULL)) {
2118 return qemu_chr_open_win(filename);
2120 if (strstart(filename, "pipe:", &p)) {
2121 return qemu_chr_open_win_pipe(p);
2123 if (strstart(filename, "file:", &p)) {
2124 return qemu_chr_open_win_file_out(p);
2132 void qemu_chr_close(CharDriverState *chr)
2135 chr->chr_close(chr);
2138 /***********************************************************/
2139 /* network device redirectors */
2141 void hex_dump(FILE *f, const uint8_t *buf, int size)
2145 for(i=0;i<size;i+=16) {
2149 fprintf(f, "%08x ", i);
2152 fprintf(f, " %02x", buf[i+j]);
2157 for(j=0;j<len;j++) {
2159 if (c < ' ' || c > '~')
2161 fprintf(f, "%c", c);
2167 static int parse_macaddr(uint8_t *macaddr, const char *p)
2170 for(i = 0; i < 6; i++) {
2171 macaddr[i] = strtol(p, (char **)&p, 16);
2184 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
2189 p1 = strchr(p, sep);
2195 if (len > buf_size - 1)
2197 memcpy(buf, p, len);
2204 int parse_host_port(struct sockaddr_in *saddr, const char *str)
2212 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2214 saddr->sin_family = AF_INET;
2215 if (buf[0] == '\0') {
2216 saddr->sin_addr.s_addr = 0;
2218 if (isdigit(buf[0])) {
2219 if (!inet_aton(buf, &saddr->sin_addr))
2222 if ((he = gethostbyname(buf)) == NULL)
2224 saddr->sin_addr = *(struct in_addr *)he->h_addr;
2227 port = strtol(p, (char **)&r, 0);
2230 saddr->sin_port = htons(port);
2234 /* find or alloc a new VLAN */
2235 VLANState *qemu_find_vlan(int id)
2237 VLANState **pvlan, *vlan;
2238 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
2242 vlan = qemu_mallocz(sizeof(VLANState));
2247 pvlan = &first_vlan;
2248 while (*pvlan != NULL)
2249 pvlan = &(*pvlan)->next;
2254 VLANClientState *qemu_new_vlan_client(VLANState *vlan,
2255 IOReadHandler *fd_read,
2256 IOCanRWHandler *fd_can_read,
2259 VLANClientState *vc, **pvc;
2260 vc = qemu_mallocz(sizeof(VLANClientState));
2263 vc->fd_read = fd_read;
2264 vc->fd_can_read = fd_can_read;
2265 vc->opaque = opaque;
2269 pvc = &vlan->first_client;
2270 while (*pvc != NULL)
2271 pvc = &(*pvc)->next;
2276 int qemu_can_send_packet(VLANClientState *vc1)
2278 VLANState *vlan = vc1->vlan;
2279 VLANClientState *vc;
2281 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
2283 if (vc->fd_can_read && !vc->fd_can_read(vc->opaque))
2290 void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
2292 VLANState *vlan = vc1->vlan;
2293 VLANClientState *vc;
2296 printf("vlan %d send:\n", vlan->id);
2297 hex_dump(stdout, buf, size);
2299 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
2301 vc->fd_read(vc->opaque, buf, size);
2306 #if defined(CONFIG_SLIRP)
2308 /* slirp network adapter */
2310 static int slirp_inited;
2311 static VLANClientState *slirp_vc;
2313 int slirp_can_output(void)
2315 return !slirp_vc || qemu_can_send_packet(slirp_vc);
2318 void slirp_output(const uint8_t *pkt, int pkt_len)
2321 printf("slirp output:\n");
2322 hex_dump(stdout, pkt, pkt_len);
2326 qemu_send_packet(slirp_vc, pkt, pkt_len);
2329 static void slirp_receive(void *opaque, const uint8_t *buf, int size)
2332 printf("slirp input:\n");
2333 hex_dump(stdout, buf, size);
2335 slirp_input(buf, size);
2338 static int net_slirp_init(VLANState *vlan)
2340 if (!slirp_inited) {
2344 slirp_vc = qemu_new_vlan_client(vlan,
2345 slirp_receive, NULL, NULL);
2346 snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
2350 static void net_slirp_redir(const char *redir_str)
2355 struct in_addr guest_addr;
2356 int host_port, guest_port;
2358 if (!slirp_inited) {
2364 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2366 if (!strcmp(buf, "tcp")) {
2368 } else if (!strcmp(buf, "udp")) {
2374 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2376 host_port = strtol(buf, &r, 0);
2380 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2382 if (buf[0] == '\0') {
2383 pstrcpy(buf, sizeof(buf), "10.0.2.15");
2385 if (!inet_aton(buf, &guest_addr))
2388 guest_port = strtol(p, &r, 0);
2392 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
2393 fprintf(stderr, "qemu: could not set up redirection\n");
2398 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
2406 static void smb_exit(void)
2410 char filename[1024];
2412 /* erase all the files in the directory */
2413 d = opendir(smb_dir);
2418 if (strcmp(de->d_name, ".") != 0 &&
2419 strcmp(de->d_name, "..") != 0) {
2420 snprintf(filename, sizeof(filename), "%s/%s",
2421 smb_dir, de->d_name);
2429 /* automatic user mode samba server configuration */
2430 void net_slirp_smb(const char *exported_dir)
2432 char smb_conf[1024];
2433 char smb_cmdline[1024];
2436 if (!slirp_inited) {
2441 /* XXX: better tmp dir construction */
2442 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
2443 if (mkdir(smb_dir, 0700) < 0) {
2444 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
2447 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
2449 f = fopen(smb_conf, "w");
2451 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
2458 "socket address=127.0.0.1\n"
2459 "pid directory=%s\n"
2460 "lock directory=%s\n"
2461 "log file=%s/log.smbd\n"
2462 "smb passwd file=%s/smbpasswd\n"
2463 "security = share\n"
2478 snprintf(smb_cmdline, sizeof(smb_cmdline), "/usr/sbin/smbd -s %s",
2481 slirp_add_exec(0, smb_cmdline, 4, 139);
2484 #endif /* !defined(_WIN32) */
2486 #endif /* CONFIG_SLIRP */
2488 #if !defined(_WIN32)
2490 typedef struct TAPState {
2491 VLANClientState *vc;
2495 static void tap_receive(void *opaque, const uint8_t *buf, int size)
2497 TAPState *s = opaque;
2500 ret = write(s->fd, buf, size);
2501 if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
2508 static void tap_send(void *opaque)
2510 TAPState *s = opaque;
2514 size = read(s->fd, buf, sizeof(buf));
2516 qemu_send_packet(s->vc, buf, size);
2522 static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
2526 s = qemu_mallocz(sizeof(TAPState));
2530 s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
2531 qemu_set_fd_handler(s->fd, tap_send, NULL, s);
2532 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
2537 static int tap_open(char *ifname, int ifname_size)
2543 fd = open("/dev/tap", O_RDWR);
2545 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
2550 dev = devname(s.st_rdev, S_IFCHR);
2551 pstrcpy(ifname, ifname_size, dev);
2553 fcntl(fd, F_SETFL, O_NONBLOCK);
2557 static int tap_open(char *ifname, int ifname_size)
2562 fd = open("/dev/net/tun", O_RDWR);
2564 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
2567 memset(&ifr, 0, sizeof(ifr));
2568 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
2569 if (ifname[0] != '\0')
2570 pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
2572 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
2573 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
2575 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
2579 pstrcpy(ifname, ifname_size, ifr.ifr_name);
2580 fcntl(fd, F_SETFL, O_NONBLOCK);
2585 static int net_tap_init(VLANState *vlan, const char *ifname1,
2586 const char *setup_script)
2589 int pid, status, fd;
2594 if (ifname1 != NULL)
2595 pstrcpy(ifname, sizeof(ifname), ifname1);
2598 fd = tap_open(ifname, sizeof(ifname));
2604 if (setup_script[0] != '\0') {
2605 /* try to launch network init script */
2610 *parg++ = (char *)setup_script;
2613 execv(setup_script, args);
2616 while (waitpid(pid, &status, 0) != pid);
2617 if (!WIFEXITED(status) ||
2618 WEXITSTATUS(status) != 0) {
2619 fprintf(stderr, "%s: could not launch network script\n",
2625 s = net_tap_fd_init(vlan, fd);
2628 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
2629 "tap: ifname=%s setup_script=%s", ifname, setup_script);
2633 #endif /* !_WIN32 */
2635 /* network connection */
2636 typedef struct NetSocketState {
2637 VLANClientState *vc;
2639 int state; /* 0 = getting length, 1 = getting data */
2643 struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
2646 typedef struct NetSocketListenState {
2649 } NetSocketListenState;
2651 /* XXX: we consider we can send the whole packet without blocking */
2652 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
2654 NetSocketState *s = opaque;
2658 send_all(s->fd, (const uint8_t *)&len, sizeof(len));
2659 send_all(s->fd, buf, size);
2662 static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
2664 NetSocketState *s = opaque;
2665 sendto(s->fd, buf, size, 0,
2666 (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
2669 static void net_socket_send(void *opaque)
2671 NetSocketState *s = opaque;
2676 size = recv(s->fd, buf1, sizeof(buf1), 0);
2678 err = socket_error();
2679 if (err != EWOULDBLOCK)
2681 } else if (size == 0) {
2682 /* end of connection */
2684 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2690 /* reassemble a packet from the network */
2696 memcpy(s->buf + s->index, buf, l);
2700 if (s->index == 4) {
2702 s->packet_len = ntohl(*(uint32_t *)s->buf);
2708 l = s->packet_len - s->index;
2711 memcpy(s->buf + s->index, buf, l);
2715 if (s->index >= s->packet_len) {
2716 qemu_send_packet(s->vc, s->buf, s->packet_len);
2725 static void net_socket_send_dgram(void *opaque)
2727 NetSocketState *s = opaque;
2730 size = recv(s->fd, s->buf, sizeof(s->buf), 0);
2734 /* end of connection */
2735 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2738 qemu_send_packet(s->vc, s->buf, size);
2741 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
2746 if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
2747 fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
2748 inet_ntoa(mcastaddr->sin_addr),
2749 (int)ntohl(mcastaddr->sin_addr.s_addr));
2753 fd = socket(PF_INET, SOCK_DGRAM, 0);
2755 perror("socket(PF_INET, SOCK_DGRAM)");
2760 ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
2761 (const char *)&val, sizeof(val));
2763 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
2767 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
2773 /* Add host to multicast group */
2774 imr.imr_multiaddr = mcastaddr->sin_addr;
2775 imr.imr_interface.s_addr = htonl(INADDR_ANY);
2777 ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
2778 (const char *)&imr, sizeof(struct ip_mreq));
2780 perror("setsockopt(IP_ADD_MEMBERSHIP)");
2784 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
2786 ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
2787 (const char *)&val, sizeof(val));
2789 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
2793 socket_set_nonblock(fd);
2796 if (fd>=0) close(fd);
2800 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd,
2803 struct sockaddr_in saddr;
2805 socklen_t saddr_len;
2808 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
2809 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
2810 * by ONLY ONE process: we must "clone" this dgram socket --jjo
2814 if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
2816 if (saddr.sin_addr.s_addr==0) {
2817 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
2821 /* clone dgram socket */
2822 newfd = net_socket_mcast_create(&saddr);
2824 /* error already reported by net_socket_mcast_create() */
2828 /* clone newfd to fd, close newfd */
2833 fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
2834 fd, strerror(errno));
2839 s = qemu_mallocz(sizeof(NetSocketState));
2844 s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
2845 qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
2847 /* mcast: save bound address as dst */
2848 if (is_connected) s->dgram_dst=saddr;
2850 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
2851 "socket: fd=%d (%s mcast=%s:%d)",
2852 fd, is_connected? "cloned" : "",
2853 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
2857 static void net_socket_connect(void *opaque)
2859 NetSocketState *s = opaque;
2860 qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
2863 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd,
2867 s = qemu_mallocz(sizeof(NetSocketState));
2871 s->vc = qemu_new_vlan_client(vlan,
2872 net_socket_receive, NULL, s);
2873 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
2874 "socket: fd=%d", fd);
2876 net_socket_connect(s);
2878 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
2883 static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
2886 int so_type=-1, optlen=sizeof(so_type);
2888 if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type, &optlen)< 0) {
2889 fprintf(stderr, "qemu: error: setsockopt(SO_TYPE) for fd=%d failed\n", fd);
2894 return net_socket_fd_init_dgram(vlan, fd, is_connected);
2896 return net_socket_fd_init_stream(vlan, fd, is_connected);
2898 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
2899 fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
2900 return net_socket_fd_init_stream(vlan, fd, is_connected);
2905 static void net_socket_accept(void *opaque)
2907 NetSocketListenState *s = opaque;
2909 struct sockaddr_in saddr;
2914 len = sizeof(saddr);
2915 fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
2916 if (fd < 0 && errno != EINTR) {
2918 } else if (fd >= 0) {
2922 s1 = net_socket_fd_init(s->vlan, fd, 1);
2926 snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
2927 "socket: connection from %s:%d",
2928 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
2932 static int net_socket_listen_init(VLANState *vlan, const char *host_str)
2934 NetSocketListenState *s;
2936 struct sockaddr_in saddr;
2938 if (parse_host_port(&saddr, host_str) < 0)
2941 s = qemu_mallocz(sizeof(NetSocketListenState));
2945 fd = socket(PF_INET, SOCK_STREAM, 0);
2950 socket_set_nonblock(fd);
2952 /* allow fast reuse */
2954 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
2956 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
2961 ret = listen(fd, 0);
2968 qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
2972 static int net_socket_connect_init(VLANState *vlan, const char *host_str)
2975 int fd, connected, ret, err;
2976 struct sockaddr_in saddr;
2978 if (parse_host_port(&saddr, host_str) < 0)
2981 fd = socket(PF_INET, SOCK_STREAM, 0);
2986 socket_set_nonblock(fd);
2990 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
2992 err = socket_error();
2993 if (err == EINTR || err == EWOULDBLOCK) {
2994 } else if (err == EINPROGRESS) {
3006 s = net_socket_fd_init(vlan, fd, connected);
3009 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3010 "socket: connect to %s:%d",
3011 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3015 static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
3019 struct sockaddr_in saddr;
3021 if (parse_host_port(&saddr, host_str) < 0)
3025 fd = net_socket_mcast_create(&saddr);
3029 s = net_socket_fd_init(vlan, fd, 0);
3033 s->dgram_dst = saddr;
3035 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3036 "socket: mcast=%s:%d",
3037 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3042 static int get_param_value(char *buf, int buf_size,
3043 const char *tag, const char *str)
3052 while (*p != '\0' && *p != '=') {
3053 if ((q - option) < sizeof(option) - 1)
3061 if (!strcmp(tag, option)) {
3063 while (*p != '\0' && *p != ',') {
3064 if ((q - buf) < buf_size - 1)
3071 while (*p != '\0' && *p != ',') {
3082 int net_client_init(const char *str)
3093 while (*p != '\0' && *p != ',') {
3094 if ((q - device) < sizeof(device) - 1)
3102 if (get_param_value(buf, sizeof(buf), "vlan", p)) {
3103 vlan_id = strtol(buf, NULL, 0);
3105 vlan = qemu_find_vlan(vlan_id);
3107 fprintf(stderr, "Could not create vlan %d\n", vlan_id);
3110 if (!strcmp(device, "nic")) {
3114 if (nb_nics >= MAX_NICS) {
3115 fprintf(stderr, "Too Many NICs\n");
3118 nd = &nd_table[nb_nics];
3119 macaddr = nd->macaddr;
3125 macaddr[5] = 0x56 + nb_nics;
3127 if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
3128 if (parse_macaddr(macaddr, buf) < 0) {
3129 fprintf(stderr, "invalid syntax for ethernet address\n");
3133 if (get_param_value(buf, sizeof(buf), "model", p)) {
3134 nd->model = strdup(buf);
3140 if (!strcmp(device, "none")) {
3141 /* does nothing. It is needed to signal that no network cards
3146 if (!strcmp(device, "user")) {
3147 ret = net_slirp_init(vlan);
3151 if (!strcmp(device, "tap")) {
3153 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
3154 fprintf(stderr, "tap: no interface name\n");
3157 ret = tap_win32_init(vlan, ifname);
3160 if (!strcmp(device, "tap")) {
3162 char setup_script[1024];
3164 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
3165 fd = strtol(buf, NULL, 0);
3167 if (net_tap_fd_init(vlan, fd))
3170 get_param_value(ifname, sizeof(ifname), "ifname", p);
3171 if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
3172 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
3174 ret = net_tap_init(vlan, ifname, setup_script);
3178 if (!strcmp(device, "socket")) {
3179 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
3181 fd = strtol(buf, NULL, 0);
3183 if (net_socket_fd_init(vlan, fd, 1))
3185 } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
3186 ret = net_socket_listen_init(vlan, buf);
3187 } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
3188 ret = net_socket_connect_init(vlan, buf);
3189 } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
3190 ret = net_socket_mcast_init(vlan, buf);
3192 fprintf(stderr, "Unknown socket options: %s\n", p);
3197 fprintf(stderr, "Unknown network device: %s\n", device);
3201 fprintf(stderr, "Could not initialize device '%s'\n", device);
3207 void do_info_network(void)
3210 VLANClientState *vc;
3212 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
3213 term_printf("VLAN %d devices:\n", vlan->id);
3214 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
3215 term_printf(" %s\n", vc->info_str);
3219 /***********************************************************/
3222 static int usb_device_add(const char *devname)
3230 for(i = 0;i < MAX_VM_USB_PORTS; i++) {
3231 if (!vm_usb_ports[i]->dev)
3234 if (i == MAX_VM_USB_PORTS)
3237 if (strstart(devname, "host:", &p)) {
3238 dev = usb_host_device_open(p);
3241 } else if (!strcmp(devname, "mouse")) {
3242 dev = usb_mouse_init();
3248 usb_attach(vm_usb_ports[i], dev);
3252 static int usb_device_del(const char *devname)
3255 int bus_num, addr, i;
3261 p = strchr(devname, '.');
3264 bus_num = strtoul(devname, NULL, 0);
3265 addr = strtoul(p + 1, NULL, 0);
3268 for(i = 0;i < MAX_VM_USB_PORTS; i++) {
3269 dev = vm_usb_ports[i]->dev;
3270 if (dev && dev->addr == addr)
3273 if (i == MAX_VM_USB_PORTS)
3275 usb_attach(vm_usb_ports[i], NULL);
3279 void do_usb_add(const char *devname)
3282 ret = usb_device_add(devname);
3284 term_printf("Could not add USB device '%s'\n", devname);
3287 void do_usb_del(const char *devname)
3290 ret = usb_device_del(devname);
3292 term_printf("Could not remove USB device '%s'\n", devname);
3299 const char *speed_str;
3302 term_printf("USB support not enabled\n");
3306 for(i = 0; i < MAX_VM_USB_PORTS; i++) {
3307 dev = vm_usb_ports[i]->dev;
3309 term_printf("Hub port %d:\n", i);
3310 switch(dev->speed) {
3314 case USB_SPEED_FULL:
3317 case USB_SPEED_HIGH:
3324 term_printf(" Device %d.%d, speed %s Mb/s\n",
3325 0, dev->addr, speed_str);
3330 /***********************************************************/
3333 static char *pid_filename;
3335 /* Remove PID file. Called on normal exit */
3337 static void remove_pidfile(void)
3339 unlink (pid_filename);
3342 static void create_pidfile(const char *filename)
3344 struct stat pidstat;
3347 /* Try to write our PID to the named file */
3348 if (stat(filename, &pidstat) < 0) {
3349 if (errno == ENOENT) {
3350 if ((f = fopen (filename, "w")) == NULL) {
3351 perror("Opening pidfile");
3354 fprintf(f, "%d\n", getpid());
3356 pid_filename = qemu_strdup(filename);
3357 if (!pid_filename) {
3358 fprintf(stderr, "Could not save PID filename");
3361 atexit(remove_pidfile);
3364 fprintf(stderr, "%s already exists. Remove it and try again.\n",
3370 /***********************************************************/
3373 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
3377 static void dumb_resize(DisplayState *ds, int w, int h)
3381 static void dumb_refresh(DisplayState *ds)
3386 void dumb_display_init(DisplayState *ds)
3391 ds->dpy_update = dumb_update;
3392 ds->dpy_resize = dumb_resize;
3393 ds->dpy_refresh = dumb_refresh;
3396 #if !defined(CONFIG_SOFTMMU)
3397 /***********************************************************/
3398 /* cpu signal handler */
3399 static void host_segv_handler(int host_signum, siginfo_t *info,
3402 if (cpu_signal_handler(host_signum, info, puc))
3404 if (stdio_nb_clients > 0)
3410 /***********************************************************/
3413 #define MAX_IO_HANDLERS 64
3415 typedef struct IOHandlerRecord {
3417 IOCanRWHandler *fd_read_poll;
3419 IOHandler *fd_write;
3421 /* temporary data */
3423 struct IOHandlerRecord *next;
3426 static IOHandlerRecord *first_io_handler;
3428 /* XXX: fd_read_poll should be suppressed, but an API change is
3429 necessary in the character devices to suppress fd_can_read(). */
3430 int qemu_set_fd_handler2(int fd,
3431 IOCanRWHandler *fd_read_poll,
3433 IOHandler *fd_write,
3436 IOHandlerRecord **pioh, *ioh;
3438 if (!fd_read && !fd_write) {
3439 pioh = &first_io_handler;
3444 if (ioh->fd == fd) {
3452 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3456 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
3459 ioh->next = first_io_handler;
3460 first_io_handler = ioh;
3463 ioh->fd_read_poll = fd_read_poll;
3464 ioh->fd_read = fd_read;
3465 ioh->fd_write = fd_write;
3466 ioh->opaque = opaque;
3471 int qemu_set_fd_handler(int fd,
3473 IOHandler *fd_write,
3476 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
3479 /***********************************************************/
3480 /* Polling handling */
3482 typedef struct PollingEntry {
3485 struct PollingEntry *next;
3488 static PollingEntry *first_polling_entry;
3490 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
3492 PollingEntry **ppe, *pe;
3493 pe = qemu_mallocz(sizeof(PollingEntry));
3497 pe->opaque = opaque;
3498 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
3503 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
3505 PollingEntry **ppe, *pe;
3506 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
3508 if (pe->func == func && pe->opaque == opaque) {
3516 /***********************************************************/
3517 /* savevm/loadvm support */
3519 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
3521 fwrite(buf, 1, size, f);
3524 void qemu_put_byte(QEMUFile *f, int v)
3529 void qemu_put_be16(QEMUFile *f, unsigned int v)
3531 qemu_put_byte(f, v >> 8);
3532 qemu_put_byte(f, v);
3535 void qemu_put_be32(QEMUFile *f, unsigned int v)
3537 qemu_put_byte(f, v >> 24);
3538 qemu_put_byte(f, v >> 16);
3539 qemu_put_byte(f, v >> 8);
3540 qemu_put_byte(f, v);
3543 void qemu_put_be64(QEMUFile *f, uint64_t v)
3545 qemu_put_be32(f, v >> 32);
3546 qemu_put_be32(f, v);
3549 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size)
3551 return fread(buf, 1, size, f);
3554 int qemu_get_byte(QEMUFile *f)
3564 unsigned int qemu_get_be16(QEMUFile *f)
3567 v = qemu_get_byte(f) << 8;
3568 v |= qemu_get_byte(f);
3572 unsigned int qemu_get_be32(QEMUFile *f)
3575 v = qemu_get_byte(f) << 24;
3576 v |= qemu_get_byte(f) << 16;
3577 v |= qemu_get_byte(f) << 8;
3578 v |= qemu_get_byte(f);
3582 uint64_t qemu_get_be64(QEMUFile *f)
3585 v = (uint64_t)qemu_get_be32(f) << 32;
3586 v |= qemu_get_be32(f);
3590 int64_t qemu_ftell(QEMUFile *f)
3595 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
3597 if (fseek(f, pos, whence) < 0)
3602 typedef struct SaveStateEntry {
3606 SaveStateHandler *save_state;
3607 LoadStateHandler *load_state;
3609 struct SaveStateEntry *next;
3612 static SaveStateEntry *first_se;
3614 int register_savevm(const char *idstr,
3617 SaveStateHandler *save_state,
3618 LoadStateHandler *load_state,
3621 SaveStateEntry *se, **pse;
3623 se = qemu_malloc(sizeof(SaveStateEntry));
3626 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
3627 se->instance_id = instance_id;
3628 se->version_id = version_id;
3629 se->save_state = save_state;
3630 se->load_state = load_state;
3631 se->opaque = opaque;
3634 /* add at the end of list */
3636 while (*pse != NULL)
3637 pse = &(*pse)->next;
3642 #define QEMU_VM_FILE_MAGIC 0x5145564d
3643 #define QEMU_VM_FILE_VERSION 0x00000001
3645 int qemu_savevm(const char *filename)
3649 int len, len_pos, cur_pos, saved_vm_running, ret;
3651 saved_vm_running = vm_running;
3654 f = fopen(filename, "wb");
3660 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
3661 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
3663 for(se = first_se; se != NULL; se = se->next) {
3665 len = strlen(se->idstr);
3666 qemu_put_byte(f, len);
3667 qemu_put_buffer(f, se->idstr, len);
3669 qemu_put_be32(f, se->instance_id);
3670 qemu_put_be32(f, se->version_id);
3672 /* record size: filled later */
3674 qemu_put_be32(f, 0);
3676 se->save_state(f, se->opaque);
3678 /* fill record size */
3680 len = ftell(f) - len_pos - 4;
3681 fseek(f, len_pos, SEEK_SET);
3682 qemu_put_be32(f, len);
3683 fseek(f, cur_pos, SEEK_SET);
3689 if (saved_vm_running)
3694 static SaveStateEntry *find_se(const char *idstr, int instance_id)
3698 for(se = first_se; se != NULL; se = se->next) {
3699 if (!strcmp(se->idstr, idstr) &&
3700 instance_id == se->instance_id)
3706 int qemu_loadvm(const char *filename)
3710 int len, cur_pos, ret, instance_id, record_len, version_id;
3711 int saved_vm_running;
3715 saved_vm_running = vm_running;
3718 f = fopen(filename, "rb");
3724 v = qemu_get_be32(f);
3725 if (v != QEMU_VM_FILE_MAGIC)
3727 v = qemu_get_be32(f);
3728 if (v != QEMU_VM_FILE_VERSION) {
3735 len = qemu_get_byte(f);
3738 qemu_get_buffer(f, idstr, len);
3740 instance_id = qemu_get_be32(f);
3741 version_id = qemu_get_be32(f);
3742 record_len = qemu_get_be32(f);
3744 printf("idstr=%s instance=0x%x version=%d len=%d\n",
3745 idstr, instance_id, version_id, record_len);
3748 se = find_se(idstr, instance_id);
3750 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
3751 instance_id, idstr);
3753 ret = se->load_state(f, se->opaque, version_id);
3755 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
3756 instance_id, idstr);
3759 /* always seek to exact end of record */
3760 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
3765 if (saved_vm_running)
3770 /***********************************************************/
3771 /* cpu save/restore */
3773 #if defined(TARGET_I386)
3775 static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
3777 qemu_put_be32(f, dt->selector);
3778 qemu_put_betl(f, dt->base);
3779 qemu_put_be32(f, dt->limit);
3780 qemu_put_be32(f, dt->flags);
3783 static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
3785 dt->selector = qemu_get_be32(f);
3786 dt->base = qemu_get_betl(f);
3787 dt->limit = qemu_get_be32(f);
3788 dt->flags = qemu_get_be32(f);
3791 void cpu_save(QEMUFile *f, void *opaque)
3793 CPUState *env = opaque;
3794 uint16_t fptag, fpus, fpuc, fpregs_format;
3798 for(i = 0; i < CPU_NB_REGS; i++)
3799 qemu_put_betls(f, &env->regs[i]);
3800 qemu_put_betls(f, &env->eip);
3801 qemu_put_betls(f, &env->eflags);
3802 hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
3803 qemu_put_be32s(f, &hflags);
3807 fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
3809 for(i = 0; i < 8; i++) {
3810 fptag |= ((!env->fptags[i]) << i);
3813 qemu_put_be16s(f, &fpuc);
3814 qemu_put_be16s(f, &fpus);
3815 qemu_put_be16s(f, &fptag);
3817 #ifdef USE_X86LDOUBLE
3822 qemu_put_be16s(f, &fpregs_format);
3824 for(i = 0; i < 8; i++) {
3825 #ifdef USE_X86LDOUBLE
3829 /* we save the real CPU data (in case of MMX usage only 'mant'
3830 contains the MMX register */
3831 cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
3832 qemu_put_be64(f, mant);
3833 qemu_put_be16(f, exp);
3836 /* if we use doubles for float emulation, we save the doubles to
3837 avoid losing information in case of MMX usage. It can give
3838 problems if the image is restored on a CPU where long
3839 doubles are used instead. */
3840 qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
3844 for(i = 0; i < 6; i++)
3845 cpu_put_seg(f, &env->segs[i]);
3846 cpu_put_seg(f, &env->ldt);
3847 cpu_put_seg(f, &env->tr);
3848 cpu_put_seg(f, &env->gdt);
3849 cpu_put_seg(f, &env->idt);
3851 qemu_put_be32s(f, &env->sysenter_cs);
3852 qemu_put_be32s(f, &env->sysenter_esp);
3853 qemu_put_be32s(f, &env->sysenter_eip);
3855 qemu_put_betls(f, &env->cr[0]);
3856 qemu_put_betls(f, &env->cr[2]);
3857 qemu_put_betls(f, &env->cr[3]);
3858 qemu_put_betls(f, &env->cr[4]);
3860 for(i = 0; i < 8; i++)
3861 qemu_put_betls(f, &env->dr[i]);
3864 qemu_put_be32s(f, &env->a20_mask);
3867 qemu_put_be32s(f, &env->mxcsr);
3868 for(i = 0; i < CPU_NB_REGS; i++) {
3869 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
3870 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
3873 #ifdef TARGET_X86_64
3874 qemu_put_be64s(f, &env->efer);
3875 qemu_put_be64s(f, &env->star);
3876 qemu_put_be64s(f, &env->lstar);
3877 qemu_put_be64s(f, &env->cstar);
3878 qemu_put_be64s(f, &env->fmask);
3879 qemu_put_be64s(f, &env->kernelgsbase);
3883 #ifdef USE_X86LDOUBLE
3884 /* XXX: add that in a FPU generic layer */
3885 union x86_longdouble {
3890 #define MANTD1(fp) (fp & ((1LL << 52) - 1))
3891 #define EXPBIAS1 1023
3892 #define EXPD1(fp) ((fp >> 52) & 0x7FF)
3893 #define SIGND1(fp) ((fp >> 32) & 0x80000000)
3895 static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
3899 p->mant = (MANTD1(temp) << 11) | (1LL << 63);
3900 /* exponent + sign */
3901 e = EXPD1(temp) - EXPBIAS1 + 16383;
3902 e |= SIGND1(temp) >> 16;
3907 int cpu_load(QEMUFile *f, void *opaque, int version_id)
3909 CPUState *env = opaque;
3912 uint16_t fpus, fpuc, fptag, fpregs_format;
3914 if (version_id != 3)
3916 for(i = 0; i < CPU_NB_REGS; i++)
3917 qemu_get_betls(f, &env->regs[i]);
3918 qemu_get_betls(f, &env->eip);
3919 qemu_get_betls(f, &env->eflags);
3920 qemu_get_be32s(f, &hflags);
3922 qemu_get_be16s(f, &fpuc);
3923 qemu_get_be16s(f, &fpus);
3924 qemu_get_be16s(f, &fptag);
3925 qemu_get_be16s(f, &fpregs_format);
3927 /* NOTE: we cannot always restore the FPU state if the image come
3928 from a host with a different 'USE_X86LDOUBLE' define. We guess
3929 if we are in an MMX state to restore correctly in that case. */
3930 guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
3931 for(i = 0; i < 8; i++) {
3935 switch(fpregs_format) {
3937 mant = qemu_get_be64(f);
3938 exp = qemu_get_be16(f);
3939 #ifdef USE_X86LDOUBLE
3940 env->fpregs[i].d = cpu_set_fp80(mant, exp);
3942 /* difficult case */
3944 env->fpregs[i].mmx.MMX_Q(0) = mant;
3946 env->fpregs[i].d = cpu_set_fp80(mant, exp);
3950 mant = qemu_get_be64(f);
3951 #ifdef USE_X86LDOUBLE
3953 union x86_longdouble *p;
3954 /* difficult case */
3955 p = (void *)&env->fpregs[i];
3960 fp64_to_fp80(p, mant);
3964 env->fpregs[i].mmx.MMX_Q(0) = mant;
3973 /* XXX: restore FPU round state */
3974 env->fpstt = (fpus >> 11) & 7;
3975 env->fpus = fpus & ~0x3800;
3977 for(i = 0; i < 8; i++) {
3978 env->fptags[i] = (fptag >> i) & 1;
3981 for(i = 0; i < 6; i++)
3982 cpu_get_seg(f, &env->segs[i]);
3983 cpu_get_seg(f, &env->ldt);
3984 cpu_get_seg(f, &env->tr);
3985 cpu_get_seg(f, &env->gdt);
3986 cpu_get_seg(f, &env->idt);
3988 qemu_get_be32s(f, &env->sysenter_cs);
3989 qemu_get_be32s(f, &env->sysenter_esp);
3990 qemu_get_be32s(f, &env->sysenter_eip);
3992 qemu_get_betls(f, &env->cr[0]);
3993 qemu_get_betls(f, &env->cr[2]);
3994 qemu_get_betls(f, &env->cr[3]);
3995 qemu_get_betls(f, &env->cr[4]);
3997 for(i = 0; i < 8; i++)
3998 qemu_get_betls(f, &env->dr[i]);
4001 qemu_get_be32s(f, &env->a20_mask);
4003 qemu_get_be32s(f, &env->mxcsr);
4004 for(i = 0; i < CPU_NB_REGS; i++) {
4005 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
4006 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
4009 #ifdef TARGET_X86_64
4010 qemu_get_be64s(f, &env->efer);
4011 qemu_get_be64s(f, &env->star);
4012 qemu_get_be64s(f, &env->lstar);
4013 qemu_get_be64s(f, &env->cstar);
4014 qemu_get_be64s(f, &env->fmask);
4015 qemu_get_be64s(f, &env->kernelgsbase);
4018 /* XXX: compute hflags from scratch, except for CPL and IIF */
4019 env->hflags = hflags;
4024 #elif defined(TARGET_PPC)
4025 void cpu_save(QEMUFile *f, void *opaque)
4029 int cpu_load(QEMUFile *f, void *opaque, int version_id)
4034 #elif defined(TARGET_MIPS)
4035 void cpu_save(QEMUFile *f, void *opaque)
4039 int cpu_load(QEMUFile *f, void *opaque, int version_id)
4044 #elif defined(TARGET_SPARC)
4045 void cpu_save(QEMUFile *f, void *opaque)
4047 CPUState *env = opaque;
4051 for(i = 0; i < 8; i++)
4052 qemu_put_betls(f, &env->gregs[i]);
4053 for(i = 0; i < NWINDOWS * 16; i++)
4054 qemu_put_betls(f, &env->regbase[i]);
4057 for(i = 0; i < TARGET_FPREGS; i++) {
4063 qemu_put_betl(f, u.i);
4066 qemu_put_betls(f, &env->pc);
4067 qemu_put_betls(f, &env->npc);
4068 qemu_put_betls(f, &env->y);
4070 qemu_put_be32(f, tmp);
4071 qemu_put_betls(f, &env->fsr);
4072 qemu_put_betls(f, &env->tbr);
4073 #ifndef TARGET_SPARC64
4074 qemu_put_be32s(f, &env->wim);
4076 for(i = 0; i < 16; i++)
4077 qemu_put_be32s(f, &env->mmuregs[i]);
4081 int cpu_load(QEMUFile *f, void *opaque, int version_id)
4083 CPUState *env = opaque;
4087 for(i = 0; i < 8; i++)
4088 qemu_get_betls(f, &env->gregs[i]);
4089 for(i = 0; i < NWINDOWS * 16; i++)
4090 qemu_get_betls(f, &env->regbase[i]);
4093 for(i = 0; i < TARGET_FPREGS; i++) {
4098 u.i = qemu_get_betl(f);
4102 qemu_get_betls(f, &env->pc);
4103 qemu_get_betls(f, &env->npc);
4104 qemu_get_betls(f, &env->y);
4105 tmp = qemu_get_be32(f);
4106 env->cwp = 0; /* needed to ensure that the wrapping registers are
4107 correctly updated */
4109 qemu_get_betls(f, &env->fsr);
4110 qemu_get_betls(f, &env->tbr);
4111 #ifndef TARGET_SPARC64
4112 qemu_get_be32s(f, &env->wim);
4114 for(i = 0; i < 16; i++)
4115 qemu_get_be32s(f, &env->mmuregs[i]);
4121 #elif defined(TARGET_ARM)
4123 /* ??? Need to implement these. */
4124 void cpu_save(QEMUFile *f, void *opaque)
4128 int cpu_load(QEMUFile *f, void *opaque, int version_id)
4135 #warning No CPU save/restore functions
4139 /***********************************************************/
4140 /* ram save/restore */
4142 /* we just avoid storing empty pages */
4143 static void ram_put_page(QEMUFile *f, const uint8_t *buf, int len)
4148 for(i = 1; i < len; i++) {
4152 qemu_put_byte(f, 1);
4153 qemu_put_byte(f, v);
4156 qemu_put_byte(f, 0);
4157 qemu_put_buffer(f, buf, len);
4160 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
4164 v = qemu_get_byte(f);
4167 if (qemu_get_buffer(f, buf, len) != len)
4171 v = qemu_get_byte(f);
4172 memset(buf, v, len);
4180 static void ram_save(QEMUFile *f, void *opaque)
4183 qemu_put_be32(f, phys_ram_size);
4184 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
4185 ram_put_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
4189 static int ram_load(QEMUFile *f, void *opaque, int version_id)
4193 if (version_id != 1)
4195 if (qemu_get_be32(f) != phys_ram_size)
4197 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
4198 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
4205 /***********************************************************/
4206 /* machine registration */
4208 QEMUMachine *first_machine = NULL;
4210 int qemu_register_machine(QEMUMachine *m)
4213 pm = &first_machine;
4221 QEMUMachine *find_machine(const char *name)
4225 for(m = first_machine; m != NULL; m = m->next) {
4226 if (!strcmp(m->name, name))
4232 /***********************************************************/
4233 /* main execution loop */
4235 void gui_update(void *opaque)
4237 display_state.dpy_refresh(&display_state);
4238 qemu_mod_timer(gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
4241 struct vm_change_state_entry {
4242 VMChangeStateHandler *cb;
4244 LIST_ENTRY (vm_change_state_entry) entries;
4247 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
4249 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
4252 VMChangeStateEntry *e;
4254 e = qemu_mallocz(sizeof (*e));
4260 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
4264 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
4266 LIST_REMOVE (e, entries);
4270 static void vm_state_notify(int running)
4272 VMChangeStateEntry *e;
4274 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
4275 e->cb(e->opaque, running);
4279 /* XXX: support several handlers */
4280 static VMStopHandler *vm_stop_cb;
4281 static void *vm_stop_opaque;
4283 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
4286 vm_stop_opaque = opaque;
4290 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
4304 void vm_stop(int reason)
4307 cpu_disable_ticks();
4311 vm_stop_cb(vm_stop_opaque, reason);
4318 /* reset/shutdown handler */
4320 typedef struct QEMUResetEntry {
4321 QEMUResetHandler *func;
4323 struct QEMUResetEntry *next;
4326 static QEMUResetEntry *first_reset_entry;
4327 static int reset_requested;
4328 static int shutdown_requested;
4329 static int powerdown_requested;
4331 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
4333 QEMUResetEntry **pre, *re;
4335 pre = &first_reset_entry;
4336 while (*pre != NULL)
4337 pre = &(*pre)->next;
4338 re = qemu_mallocz(sizeof(QEMUResetEntry));
4340 re->opaque = opaque;
4345 void qemu_system_reset(void)
4349 /* reset all devices */
4350 for(re = first_reset_entry; re != NULL; re = re->next) {
4351 re->func(re->opaque);
4355 void qemu_system_reset_request(void)
4357 reset_requested = 1;
4359 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
4362 void qemu_system_shutdown_request(void)
4364 shutdown_requested = 1;
4366 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
4369 void qemu_system_powerdown_request(void)
4371 powerdown_requested = 1;
4373 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
4376 void main_loop_wait(int timeout)
4378 IOHandlerRecord *ioh, *ioh_next;
4385 /* XXX: need to suppress polling by better using win32 events */
4387 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
4388 ret |= pe->func(pe->opaque);
4391 if (ret == 0 && timeout > 0) {
4395 /* poll any events */
4396 /* XXX: separate device handlers from system ones */
4400 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4402 (!ioh->fd_read_poll ||
4403 ioh->fd_read_poll(ioh->opaque) != 0)) {
4404 FD_SET(ioh->fd, &rfds);
4408 if (ioh->fd_write) {
4409 FD_SET(ioh->fd, &wfds);
4419 tv.tv_usec = timeout * 1000;
4421 ret = select(nfds + 1, &rfds, &wfds, NULL, &tv);
4423 /* XXX: better handling of removal */
4424 for(ioh = first_io_handler; ioh != NULL; ioh = ioh_next) {
4425 ioh_next = ioh->next;
4426 if (FD_ISSET(ioh->fd, &rfds)) {
4427 ioh->fd_read(ioh->opaque);
4429 if (FD_ISSET(ioh->fd, &wfds)) {
4430 ioh->fd_write(ioh->opaque);
4438 #if defined(CONFIG_SLIRP)
4439 /* XXX: merge with the previous select() */
4441 fd_set rfds, wfds, xfds;
4449 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
4452 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
4454 slirp_select_poll(&rfds, &wfds, &xfds);
4460 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
4461 qemu_get_clock(vm_clock));
4462 /* run dma transfers, if any */
4466 /* real time timers */
4467 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
4468 qemu_get_clock(rt_clock));
4471 static CPUState *cur_cpu;
4476 #ifdef CONFIG_PROFILER
4481 cur_cpu = first_cpu;
4488 env = env->next_cpu;
4491 #ifdef CONFIG_PROFILER
4492 ti = profile_getclock();
4494 ret = cpu_exec(env);
4495 #ifdef CONFIG_PROFILER
4496 qemu_time += profile_getclock() - ti;
4498 if (ret != EXCP_HALTED)
4500 /* all CPUs are halted ? */
4501 if (env == cur_cpu) {
4508 if (shutdown_requested) {
4509 ret = EXCP_INTERRUPT;
4512 if (reset_requested) {
4513 reset_requested = 0;
4514 qemu_system_reset();
4515 ret = EXCP_INTERRUPT;
4517 if (powerdown_requested) {
4518 powerdown_requested = 0;
4519 qemu_system_powerdown();
4520 ret = EXCP_INTERRUPT;
4522 if (ret == EXCP_DEBUG) {
4523 vm_stop(EXCP_DEBUG);
4525 /* if hlt instruction, we wait until the next IRQ */
4526 /* XXX: use timeout computed from timers */
4527 if (ret == EXCP_HLT)
4534 #ifdef CONFIG_PROFILER
4535 ti = profile_getclock();
4537 main_loop_wait(timeout);
4538 #ifdef CONFIG_PROFILER
4539 dev_time += profile_getclock() - ti;
4542 cpu_disable_ticks();
4548 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2005 Fabrice Bellard\n"
4549 "usage: %s [options] [disk_image]\n"
4551 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4553 "Standard options:\n"
4554 "-M machine select emulated machine (-M ? for list)\n"
4555 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
4556 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
4557 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
4558 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
4559 "-boot [a|c|d] boot on floppy (a), hard disk (c) or CD-ROM (d)\n"
4560 "-snapshot write to temporary files instead of disk image files\n"
4561 "-m megs set virtual RAM size to megs MB [default=%d]\n"
4562 "-smp n set the number of CPUs to 'n' [default=1]\n"
4563 "-nographic disable graphical output and redirect serial I/Os to console\n"
4565 "-k language use keyboard layout (for example \"fr\" for French)\n"
4568 "-audio-help print list of audio drivers and their options\n"
4569 "-soundhw c1,... enable audio support\n"
4570 " and only specified sound cards (comma separated list)\n"
4571 " use -soundhw ? to get the list of supported cards\n"
4572 " use -soundhw all to enable all of them\n"
4574 "-localtime set the real time clock to local time [default=utc]\n"
4575 "-full-screen start in full screen\n"
4577 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
4579 "-usb enable the USB driver (will be the default soon)\n"
4580 "-usbdevice name add the host or guest USB device 'name'\n"
4581 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
4582 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
4585 "Network options:\n"
4586 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
4587 " create a new Network Interface Card and connect it to VLAN 'n'\n"
4589 "-net user[,vlan=n]\n"
4590 " connect the user mode network stack to VLAN 'n'\n"
4593 "-net tap[,vlan=n],ifname=name\n"
4594 " connect the host TAP network interface to VLAN 'n'\n"
4596 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file]\n"
4597 " connect the host TAP network interface to VLAN 'n' and use\n"
4598 " the network script 'file' (default=%s);\n"
4599 " use 'fd=h' to connect to an already opened TAP interface\n"
4601 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
4602 " connect the vlan 'n' to another VLAN using a socket connection\n"
4603 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
4604 " connect the vlan 'n' to multicast maddr and port\n"
4605 "-net none use it alone to have zero network devices; if no -net option\n"
4606 " is provided, the default is '-net nic -net user'\n"
4609 "-tftp prefix allow tftp access to files starting with prefix [-net user]\n"
4611 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
4613 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
4614 " redirect TCP or UDP connections from host to guest [-net user]\n"
4617 "Linux boot specific:\n"
4618 "-kernel bzImage use 'bzImage' as kernel image\n"
4619 "-append cmdline use 'cmdline' as kernel command line\n"
4620 "-initrd file use 'file' as initial ram disk\n"
4622 "Debug/Expert options:\n"
4623 "-monitor dev redirect the monitor to char device 'dev'\n"
4624 "-serial dev redirect the serial port to char device 'dev'\n"
4625 "-parallel dev redirect the parallel port to char device 'dev'\n"
4626 "-pidfile file Write PID to 'file'\n"
4627 "-S freeze CPU at startup (use 'c' to start execution)\n"
4628 "-s wait gdb connection to port %d\n"
4629 "-p port change gdb connection port\n"
4630 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
4631 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
4632 " translation (t=none or lba) (usually qemu can guess them)\n"
4633 "-L path set the directory for the BIOS and VGA BIOS\n"
4635 "-no-kqemu disable KQEMU kernel module usage\n"
4637 #ifdef USE_CODE_COPY
4638 "-no-code-copy disable code copy acceleration\n"
4641 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
4642 " (default is CL-GD5446 PCI VGA)\n"
4644 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
4646 "During emulation, the following keys are useful:\n"
4647 "ctrl-alt-f toggle full screen\n"
4648 "ctrl-alt-n switch to virtual console 'n'\n"
4649 "ctrl-alt toggle mouse and keyboard grab\n"
4651 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4653 #ifdef CONFIG_SOFTMMU
4660 DEFAULT_NETWORK_SCRIPT,
4662 DEFAULT_GDBSTUB_PORT,
4664 #ifndef CONFIG_SOFTMMU
4666 "NOTE: this version of QEMU is faster but it needs slightly patched OSes to\n"
4667 "work. Please use the 'qemu' executable to have a more accurate (but slower)\n"
4673 #define HAS_ARG 0x0001
4687 QEMU_OPTION_snapshot,
4689 QEMU_OPTION_nographic,
4691 QEMU_OPTION_audio_help,
4692 QEMU_OPTION_soundhw,
4710 QEMU_OPTION_no_code_copy,
4712 QEMU_OPTION_localtime,
4713 QEMU_OPTION_cirrusvga,
4715 QEMU_OPTION_std_vga,
4716 QEMU_OPTION_monitor,
4718 QEMU_OPTION_parallel,
4720 QEMU_OPTION_full_screen,
4721 QEMU_OPTION_pidfile,
4722 QEMU_OPTION_no_kqemu,
4723 QEMU_OPTION_kernel_kqemu,
4724 QEMU_OPTION_win2k_hack,
4726 QEMU_OPTION_usbdevice,
4730 typedef struct QEMUOption {
4736 const QEMUOption qemu_options[] = {
4737 { "h", 0, QEMU_OPTION_h },
4739 { "M", HAS_ARG, QEMU_OPTION_M },
4740 { "fda", HAS_ARG, QEMU_OPTION_fda },
4741 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
4742 { "hda", HAS_ARG, QEMU_OPTION_hda },
4743 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
4744 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
4745 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
4746 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
4747 { "boot", HAS_ARG, QEMU_OPTION_boot },
4748 { "snapshot", 0, QEMU_OPTION_snapshot },
4749 { "m", HAS_ARG, QEMU_OPTION_m },
4750 { "nographic", 0, QEMU_OPTION_nographic },
4751 { "k", HAS_ARG, QEMU_OPTION_k },
4753 { "audio-help", 0, QEMU_OPTION_audio_help },
4754 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
4757 { "net", HAS_ARG, QEMU_OPTION_net},
4759 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
4761 { "smb", HAS_ARG, QEMU_OPTION_smb },
4763 { "redir", HAS_ARG, QEMU_OPTION_redir },
4766 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
4767 { "append", HAS_ARG, QEMU_OPTION_append },
4768 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
4770 { "S", 0, QEMU_OPTION_S },
4771 { "s", 0, QEMU_OPTION_s },
4772 { "p", HAS_ARG, QEMU_OPTION_p },
4773 { "d", HAS_ARG, QEMU_OPTION_d },
4774 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
4775 { "L", HAS_ARG, QEMU_OPTION_L },
4776 { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
4778 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
4779 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
4781 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
4782 { "g", 1, QEMU_OPTION_g },
4784 { "localtime", 0, QEMU_OPTION_localtime },
4785 { "std-vga", 0, QEMU_OPTION_std_vga },
4786 { "monitor", 1, QEMU_OPTION_monitor },
4787 { "serial", 1, QEMU_OPTION_serial },
4788 { "parallel", 1, QEMU_OPTION_parallel },
4789 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
4790 { "full-screen", 0, QEMU_OPTION_full_screen },
4791 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
4792 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
4793 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
4794 { "smp", HAS_ARG, QEMU_OPTION_smp },
4796 /* temporary options */
4797 { "usb", 0, QEMU_OPTION_usb },
4798 { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
4802 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
4804 /* this stack is only used during signal handling */
4805 #define SIGNAL_STACK_SIZE 32768
4807 static uint8_t *signal_stack;
4811 /* password input */
4813 static BlockDriverState *get_bdrv(int index)
4815 BlockDriverState *bs;
4818 bs = bs_table[index];
4819 } else if (index < 6) {
4820 bs = fd_table[index - 4];
4827 static void read_passwords(void)
4829 BlockDriverState *bs;
4833 for(i = 0; i < 6; i++) {
4835 if (bs && bdrv_is_encrypted(bs)) {
4836 term_printf("%s is encrypted.\n", bdrv_get_device_name(bs));
4837 for(j = 0; j < 3; j++) {
4838 monitor_readline("Password: ",
4839 1, password, sizeof(password));
4840 if (bdrv_set_key(bs, password) == 0)
4842 term_printf("invalid password\n");
4848 /* XXX: currently we cannot use simultaneously different CPUs */
4849 void register_machines(void)
4851 #if defined(TARGET_I386)
4852 qemu_register_machine(&pc_machine);
4853 qemu_register_machine(&isapc_machine);
4854 #elif defined(TARGET_PPC)
4855 qemu_register_machine(&heathrow_machine);
4856 qemu_register_machine(&core99_machine);
4857 qemu_register_machine(&prep_machine);
4858 #elif defined(TARGET_MIPS)
4859 qemu_register_machine(&mips_machine);
4860 #elif defined(TARGET_SPARC)
4861 #ifdef TARGET_SPARC64
4862 qemu_register_machine(&sun4u_machine);
4864 qemu_register_machine(&sun4m_machine);
4866 #elif defined(TARGET_ARM)
4867 qemu_register_machine(&integratorcp926_machine);
4868 qemu_register_machine(&integratorcp1026_machine);
4869 qemu_register_machine(&versatilepb_machine);
4871 #error unsupported CPU
4876 struct soundhw soundhw[] = {
4879 "Creative Sound Blaster 16",
4882 { .init_isa = SB16_init }
4889 "Yamaha YMF262 (OPL3)",
4891 "Yamaha YM3812 (OPL2)",
4895 { .init_isa = Adlib_init }
4902 "Gravis Ultrasound GF1",
4905 { .init_isa = GUS_init }
4911 "ENSONIQ AudioPCI ES1370",
4914 { .init_pci = es1370_init }
4917 { NULL, NULL, 0, 0, { NULL } }
4920 static void select_soundhw (const char *optarg)
4924 if (*optarg == '?') {
4927 printf ("Valid sound card names (comma separated):\n");
4928 for (c = soundhw; c->name; ++c) {
4929 printf ("%-11s %s\n", c->name, c->descr);
4931 printf ("\n-soundhw all will enable all of the above\n");
4932 exit (*optarg != '?');
4940 if (!strcmp (optarg, "all")) {
4941 for (c = soundhw; c->name; ++c) {
4949 e = strchr (p, ',');
4950 l = !e ? strlen (p) : (size_t) (e - p);
4952 for (c = soundhw; c->name; ++c) {
4953 if (!strncmp (c->name, p, l)) {
4962 "Unknown sound card name (too big to show)\n");
4965 fprintf (stderr, "Unknown sound card name `%.*s'\n",
4970 p += l + (e != NULL);
4974 goto show_valid_cards;
4979 #define MAX_NET_CLIENTS 32
4981 int main(int argc, char **argv)
4983 #ifdef CONFIG_GDBSTUB
4984 int use_gdbstub, gdbstub_port;
4987 int snapshot, linux_boot;
4988 const char *initrd_filename;
4989 const char *hd_filename[MAX_DISKS], *fd_filename[MAX_FD];
4990 const char *kernel_filename, *kernel_cmdline;
4991 DisplayState *ds = &display_state;
4992 int cyls, heads, secs, translation;
4993 int start_emulation = 1;
4994 char net_clients[MAX_NET_CLIENTS][256];
4997 const char *r, *optarg;
4998 CharDriverState *monitor_hd;
4999 char monitor_device[128];
5000 char serial_devices[MAX_SERIAL_PORTS][128];
5001 int serial_device_index;
5002 char parallel_devices[MAX_PARALLEL_PORTS][128];
5003 int parallel_device_index;
5004 const char *loadvm = NULL;
5005 QEMUMachine *machine;
5006 char usb_devices[MAX_VM_USB_PORTS][128];
5007 int usb_devices_index;
5009 LIST_INIT (&vm_change_state_head);
5010 #if !defined(CONFIG_SOFTMMU)
5011 /* we never want that malloc() uses mmap() */
5012 mallopt(M_MMAP_THRESHOLD, 4096 * 1024);
5014 register_machines();
5015 machine = first_machine;
5016 initrd_filename = NULL;
5017 for(i = 0; i < MAX_FD; i++)
5018 fd_filename[i] = NULL;
5019 for(i = 0; i < MAX_DISKS; i++)
5020 hd_filename[i] = NULL;
5021 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5022 vga_ram_size = VGA_RAM_SIZE;
5023 bios_size = BIOS_SIZE;
5024 #ifdef CONFIG_GDBSTUB
5026 gdbstub_port = DEFAULT_GDBSTUB_PORT;
5030 kernel_filename = NULL;
5031 kernel_cmdline = "";
5037 cyls = heads = secs = 0;
5038 translation = BIOS_ATA_TRANSLATION_AUTO;
5039 pstrcpy(monitor_device, sizeof(monitor_device), "vc");
5041 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
5042 for(i = 1; i < MAX_SERIAL_PORTS; i++)
5043 serial_devices[i][0] = '\0';
5044 serial_device_index = 0;
5046 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
5047 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
5048 parallel_devices[i][0] = '\0';
5049 parallel_device_index = 0;
5051 usb_devices_index = 0;
5056 /* default mac address of the first network interface */
5064 hd_filename[0] = argv[optind++];
5066 const QEMUOption *popt;
5069 popt = qemu_options;
5072 fprintf(stderr, "%s: invalid option -- '%s'\n",
5076 if (!strcmp(popt->name, r + 1))
5080 if (popt->flags & HAS_ARG) {
5081 if (optind >= argc) {
5082 fprintf(stderr, "%s: option '%s' requires an argument\n",
5086 optarg = argv[optind++];
5091 switch(popt->index) {
5093 machine = find_machine(optarg);
5096 printf("Supported machines are:\n");
5097 for(m = first_machine; m != NULL; m = m->next) {
5098 printf("%-10s %s%s\n",
5100 m == first_machine ? " (default)" : "");
5105 case QEMU_OPTION_initrd:
5106 initrd_filename = optarg;
5108 case QEMU_OPTION_hda:
5109 case QEMU_OPTION_hdb:
5110 case QEMU_OPTION_hdc:
5111 case QEMU_OPTION_hdd:
5114 hd_index = popt->index - QEMU_OPTION_hda;
5115 hd_filename[hd_index] = optarg;
5116 if (hd_index == cdrom_index)
5120 case QEMU_OPTION_snapshot:
5123 case QEMU_OPTION_hdachs:
5127 cyls = strtol(p, (char **)&p, 0);
5128 if (cyls < 1 || cyls > 16383)
5133 heads = strtol(p, (char **)&p, 0);
5134 if (heads < 1 || heads > 16)
5139 secs = strtol(p, (char **)&p, 0);
5140 if (secs < 1 || secs > 63)
5144 if (!strcmp(p, "none"))
5145 translation = BIOS_ATA_TRANSLATION_NONE;
5146 else if (!strcmp(p, "lba"))
5147 translation = BIOS_ATA_TRANSLATION_LBA;
5148 else if (!strcmp(p, "auto"))
5149 translation = BIOS_ATA_TRANSLATION_AUTO;
5152 } else if (*p != '\0') {
5154 fprintf(stderr, "qemu: invalid physical CHS format\n");
5159 case QEMU_OPTION_nographic:
5160 pstrcpy(monitor_device, sizeof(monitor_device), "stdio");
5161 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "stdio");
5164 case QEMU_OPTION_kernel:
5165 kernel_filename = optarg;
5167 case QEMU_OPTION_append:
5168 kernel_cmdline = optarg;
5170 case QEMU_OPTION_cdrom:
5171 if (cdrom_index >= 0) {
5172 hd_filename[cdrom_index] = optarg;
5175 case QEMU_OPTION_boot:
5176 boot_device = optarg[0];
5177 if (boot_device != 'a' &&
5180 boot_device != 'n' &&
5182 boot_device != 'c' && boot_device != 'd') {
5183 fprintf(stderr, "qemu: invalid boot device '%c'\n", boot_device);
5187 case QEMU_OPTION_fda:
5188 fd_filename[0] = optarg;
5190 case QEMU_OPTION_fdb:
5191 fd_filename[1] = optarg;
5193 case QEMU_OPTION_no_code_copy:
5194 code_copy_enabled = 0;
5196 case QEMU_OPTION_net:
5197 if (nb_net_clients >= MAX_NET_CLIENTS) {
5198 fprintf(stderr, "qemu: too many network clients\n");
5201 pstrcpy(net_clients[nb_net_clients],
5202 sizeof(net_clients[0]),
5207 case QEMU_OPTION_tftp:
5208 tftp_prefix = optarg;
5211 case QEMU_OPTION_smb:
5212 net_slirp_smb(optarg);
5215 case QEMU_OPTION_redir:
5216 net_slirp_redir(optarg);
5220 case QEMU_OPTION_audio_help:
5224 case QEMU_OPTION_soundhw:
5225 select_soundhw (optarg);
5232 ram_size = atoi(optarg) * 1024 * 1024;
5235 if (ram_size > PHYS_RAM_MAX_SIZE) {
5236 fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
5237 PHYS_RAM_MAX_SIZE / (1024 * 1024));
5246 mask = cpu_str_to_log_mask(optarg);
5248 printf("Log items (comma separated):\n");
5249 for(item = cpu_log_items; item->mask != 0; item++) {
5250 printf("%-10s %s\n", item->name, item->help);
5257 #ifdef CONFIG_GDBSTUB
5262 gdbstub_port = atoi(optarg);
5269 start_emulation = 0;
5272 keyboard_layout = optarg;
5274 case QEMU_OPTION_localtime:
5277 case QEMU_OPTION_cirrusvga:
5278 cirrus_vga_enabled = 1;
5280 case QEMU_OPTION_std_vga:
5281 cirrus_vga_enabled = 0;
5288 w = strtol(p, (char **)&p, 10);
5291 fprintf(stderr, "qemu: invalid resolution or depth\n");
5297 h = strtol(p, (char **)&p, 10);
5302 depth = strtol(p, (char **)&p, 10);
5303 if (depth != 8 && depth != 15 && depth != 16 &&
5304 depth != 24 && depth != 32)
5306 } else if (*p == '\0') {
5307 depth = graphic_depth;
5314 graphic_depth = depth;
5317 case QEMU_OPTION_monitor:
5318 pstrcpy(monitor_device, sizeof(monitor_device), optarg);
5320 case QEMU_OPTION_serial:
5321 if (serial_device_index >= MAX_SERIAL_PORTS) {
5322 fprintf(stderr, "qemu: too many serial ports\n");
5325 pstrcpy(serial_devices[serial_device_index],
5326 sizeof(serial_devices[0]), optarg);
5327 serial_device_index++;
5329 case QEMU_OPTION_parallel:
5330 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
5331 fprintf(stderr, "qemu: too many parallel ports\n");
5334 pstrcpy(parallel_devices[parallel_device_index],
5335 sizeof(parallel_devices[0]), optarg);
5336 parallel_device_index++;
5338 case QEMU_OPTION_loadvm:
5341 case QEMU_OPTION_full_screen:
5344 case QEMU_OPTION_pidfile:
5345 create_pidfile(optarg);
5348 case QEMU_OPTION_win2k_hack:
5349 win2k_install_hack = 1;
5353 case QEMU_OPTION_no_kqemu:
5356 case QEMU_OPTION_kernel_kqemu:
5360 case QEMU_OPTION_usb:
5363 case QEMU_OPTION_usbdevice:
5365 if (usb_devices_index >= MAX_VM_USB_PORTS) {
5366 fprintf(stderr, "Too many USB devices\n");
5369 pstrcpy(usb_devices[usb_devices_index],
5370 sizeof(usb_devices[usb_devices_index]),
5372 usb_devices_index++;
5374 case QEMU_OPTION_smp:
5375 smp_cpus = atoi(optarg);
5376 if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
5377 fprintf(stderr, "Invalid number of CPUs\n");
5389 linux_boot = (kernel_filename != NULL);
5392 hd_filename[0] == '\0' &&
5393 (cdrom_index >= 0 && hd_filename[cdrom_index] == '\0') &&
5394 fd_filename[0] == '\0')
5397 /* boot to cd by default if no hard disk */
5398 if (hd_filename[0] == '\0' && boot_device == 'c') {
5399 if (fd_filename[0] != '\0')
5405 #if !defined(CONFIG_SOFTMMU)
5406 /* must avoid mmap() usage of glibc by setting a buffer "by hand" */
5408 static uint8_t stdout_buf[4096];
5409 setvbuf(stdout, stdout_buf, _IOLBF, sizeof(stdout_buf));
5412 setvbuf(stdout, NULL, _IOLBF, 0);
5419 /* init network clients */
5420 if (nb_net_clients == 0) {
5421 /* if no clients, we use a default config */
5422 pstrcpy(net_clients[0], sizeof(net_clients[0]),
5424 pstrcpy(net_clients[1], sizeof(net_clients[0]),
5429 for(i = 0;i < nb_net_clients; i++) {
5430 if (net_client_init(net_clients[i]) < 0)
5434 /* init the memory */
5435 phys_ram_size = ram_size + vga_ram_size + bios_size;
5437 #ifdef CONFIG_SOFTMMU
5438 phys_ram_base = qemu_vmalloc(phys_ram_size);
5439 if (!phys_ram_base) {
5440 fprintf(stderr, "Could not allocate physical memory\n");
5444 /* as we must map the same page at several addresses, we must use
5449 tmpdir = getenv("QEMU_TMPDIR");
5452 snprintf(phys_ram_file, sizeof(phys_ram_file), "%s/vlXXXXXX", tmpdir);
5453 if (mkstemp(phys_ram_file) < 0) {
5454 fprintf(stderr, "Could not create temporary memory file '%s'\n",
5458 phys_ram_fd = open(phys_ram_file, O_CREAT | O_TRUNC | O_RDWR, 0600);
5459 if (phys_ram_fd < 0) {
5460 fprintf(stderr, "Could not open temporary memory file '%s'\n",
5464 ftruncate(phys_ram_fd, phys_ram_size);
5465 unlink(phys_ram_file);
5466 phys_ram_base = mmap(get_mmap_addr(phys_ram_size),
5468 PROT_WRITE | PROT_READ, MAP_SHARED | MAP_FIXED,
5470 if (phys_ram_base == MAP_FAILED) {
5471 fprintf(stderr, "Could not map physical memory\n");
5477 /* we always create the cdrom drive, even if no disk is there */
5479 if (cdrom_index >= 0) {
5480 bs_table[cdrom_index] = bdrv_new("cdrom");
5481 bdrv_set_type_hint(bs_table[cdrom_index], BDRV_TYPE_CDROM);
5484 /* open the virtual block devices */
5485 for(i = 0; i < MAX_DISKS; i++) {
5486 if (hd_filename[i]) {
5489 snprintf(buf, sizeof(buf), "hd%c", i + 'a');
5490 bs_table[i] = bdrv_new(buf);
5492 if (bdrv_open(bs_table[i], hd_filename[i], snapshot) < 0) {
5493 fprintf(stderr, "qemu: could not open hard disk image '%s'\n",
5497 if (i == 0 && cyls != 0) {
5498 bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
5499 bdrv_set_translation_hint(bs_table[i], translation);
5504 /* we always create at least one floppy disk */
5505 fd_table[0] = bdrv_new("fda");
5506 bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
5508 for(i = 0; i < MAX_FD; i++) {
5509 if (fd_filename[i]) {
5512 snprintf(buf, sizeof(buf), "fd%c", i + 'a');
5513 fd_table[i] = bdrv_new(buf);
5514 bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
5516 if (fd_filename[i] != '\0') {
5517 if (bdrv_open(fd_table[i], fd_filename[i], snapshot) < 0) {
5518 fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
5526 /* init USB devices */
5528 vm_usb_hub = usb_hub_init(vm_usb_ports, MAX_VM_USB_PORTS);
5529 for(i = 0; i < usb_devices_index; i++) {
5530 if (usb_device_add(usb_devices[i]) < 0) {
5531 fprintf(stderr, "Warning: could not add USB device %s\n",
5537 register_savevm("timer", 0, 1, timer_save, timer_load, NULL);
5538 register_savevm("ram", 0, 1, ram_save, ram_load, NULL);
5541 cpu_calibrate_ticks();
5545 dumb_display_init(ds);
5547 #if defined(CONFIG_SDL)
5548 sdl_display_init(ds, full_screen);
5549 #elif defined(CONFIG_COCOA)
5550 cocoa_display_init(ds, full_screen);
5552 dumb_display_init(ds);
5556 monitor_hd = qemu_chr_open(monitor_device);
5558 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
5561 monitor_init(monitor_hd, !nographic);
5563 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5564 if (serial_devices[i][0] != '\0') {
5565 serial_hds[i] = qemu_chr_open(serial_devices[i]);
5566 if (!serial_hds[i]) {
5567 fprintf(stderr, "qemu: could not open serial device '%s'\n",
5571 if (!strcmp(serial_devices[i], "vc"))
5572 qemu_chr_printf(serial_hds[i], "serial%d console\n", i);
5576 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5577 if (parallel_devices[i][0] != '\0') {
5578 parallel_hds[i] = qemu_chr_open(parallel_devices[i]);
5579 if (!parallel_hds[i]) {
5580 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
5581 parallel_devices[i]);
5584 if (!strcmp(parallel_devices[i], "vc"))
5585 qemu_chr_printf(parallel_hds[i], "parallel%d console\n", i);
5589 /* setup cpu signal handlers for MMU / self modifying code handling */
5590 #if !defined(CONFIG_SOFTMMU)
5592 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
5595 signal_stack = memalign(16, SIGNAL_STACK_SIZE);
5596 stk.ss_sp = signal_stack;
5597 stk.ss_size = SIGNAL_STACK_SIZE;
5600 if (sigaltstack(&stk, NULL) < 0) {
5601 perror("sigaltstack");
5607 struct sigaction act;
5609 sigfillset(&act.sa_mask);
5610 act.sa_flags = SA_SIGINFO;
5611 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
5612 act.sa_flags |= SA_ONSTACK;
5614 act.sa_sigaction = host_segv_handler;
5615 sigaction(SIGSEGV, &act, NULL);
5616 sigaction(SIGBUS, &act, NULL);
5617 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
5618 sigaction(SIGFPE, &act, NULL);
5625 struct sigaction act;
5626 sigfillset(&act.sa_mask);
5628 act.sa_handler = SIG_IGN;
5629 sigaction(SIGPIPE, &act, NULL);
5634 machine->init(ram_size, vga_ram_size, boot_device,
5635 ds, fd_filename, snapshot,
5636 kernel_filename, kernel_cmdline, initrd_filename);
5638 gui_timer = qemu_new_timer(rt_clock, gui_update, NULL);
5639 qemu_mod_timer(gui_timer, qemu_get_clock(rt_clock));
5641 #ifdef CONFIG_GDBSTUB
5643 if (gdbserver_start(gdbstub_port) < 0) {
5644 fprintf(stderr, "Could not open gdbserver socket on port %d\n",
5648 printf("Waiting gdb connection on port %d\n", gdbstub_port);
5653 qemu_loadvm(loadvm);
5656 /* XXX: simplify init */
5658 if (start_emulation) {