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>
52 #include <linux/if_tun.h>
55 #include <linux/rtc.h>
56 #include <linux/ppdev.h>
61 #if defined(CONFIG_SLIRP)
67 #include <sys/timeb.h>
71 #define getopt_long_only getopt_long
72 #define memalign(align, size) malloc(size)
79 #endif /* CONFIG_SDL */
83 #define main qemu_main
84 #endif /* CONFIG_COCOA */
90 #define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
92 //#define DEBUG_UNUSED_IOPORT
93 //#define DEBUG_IOPORT
95 #if !defined(CONFIG_SOFTMMU)
96 #define PHYS_RAM_MAX_SIZE (256 * 1024 * 1024)
98 #define PHYS_RAM_MAX_SIZE (2047 * 1024 * 1024)
102 #define DEFAULT_RAM_SIZE 144
104 #define DEFAULT_RAM_SIZE 128
107 #define GUI_REFRESH_INTERVAL 30
109 /* XXX: use a two level table to limit memory usage */
110 #define MAX_IOPORTS 65536
112 const char *bios_dir = CONFIG_QEMU_SHAREDIR;
113 char phys_ram_file[1024];
114 void *ioport_opaque[MAX_IOPORTS];
115 IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
116 IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
117 BlockDriverState *bs_table[MAX_DISKS], *fd_table[MAX_FD];
120 static DisplayState display_state;
122 const char* keyboard_layout = NULL;
123 int64_t ticks_per_sec;
124 int boot_device = 'c';
126 int pit_min_timer_count = 0;
128 NICInfo nd_table[MAX_NICS];
129 QEMUTimer *gui_timer;
132 int cirrus_vga_enabled = 1;
134 int graphic_width = 1024;
135 int graphic_height = 768;
137 int graphic_width = 800;
138 int graphic_height = 600;
140 int graphic_depth = 15;
142 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
143 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
145 int win2k_install_hack = 0;
148 USBPort *vm_usb_ports[MAX_VM_USB_PORTS];
149 USBDevice *vm_usb_hub;
150 static VLANState *first_vlan;
152 #if defined(TARGET_SPARC)
154 #elif defined(TARGET_I386)
160 /***********************************************************/
161 /* x86 ISA bus support */
163 target_phys_addr_t isa_mem_base = 0;
166 uint32_t default_ioport_readb(void *opaque, uint32_t address)
168 #ifdef DEBUG_UNUSED_IOPORT
169 fprintf(stderr, "inb: port=0x%04x\n", address);
174 void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
176 #ifdef DEBUG_UNUSED_IOPORT
177 fprintf(stderr, "outb: port=0x%04x data=0x%02x\n", address, data);
181 /* default is to make two byte accesses */
182 uint32_t default_ioport_readw(void *opaque, uint32_t address)
185 data = ioport_read_table[0][address](ioport_opaque[address], address);
186 address = (address + 1) & (MAX_IOPORTS - 1);
187 data |= ioport_read_table[0][address](ioport_opaque[address], address) << 8;
191 void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
193 ioport_write_table[0][address](ioport_opaque[address], address, data & 0xff);
194 address = (address + 1) & (MAX_IOPORTS - 1);
195 ioport_write_table[0][address](ioport_opaque[address], address, (data >> 8) & 0xff);
198 uint32_t default_ioport_readl(void *opaque, uint32_t address)
200 #ifdef DEBUG_UNUSED_IOPORT
201 fprintf(stderr, "inl: port=0x%04x\n", address);
206 void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
208 #ifdef DEBUG_UNUSED_IOPORT
209 fprintf(stderr, "outl: port=0x%04x data=0x%02x\n", address, data);
213 void init_ioports(void)
217 for(i = 0; i < MAX_IOPORTS; i++) {
218 ioport_read_table[0][i] = default_ioport_readb;
219 ioport_write_table[0][i] = default_ioport_writeb;
220 ioport_read_table[1][i] = default_ioport_readw;
221 ioport_write_table[1][i] = default_ioport_writew;
222 ioport_read_table[2][i] = default_ioport_readl;
223 ioport_write_table[2][i] = default_ioport_writel;
227 /* size is the word size in byte */
228 int register_ioport_read(int start, int length, int size,
229 IOPortReadFunc *func, void *opaque)
235 } else if (size == 2) {
237 } else if (size == 4) {
240 hw_error("register_ioport_read: invalid size");
243 for(i = start; i < start + length; i += size) {
244 ioport_read_table[bsize][i] = func;
245 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
246 hw_error("register_ioport_read: invalid opaque");
247 ioport_opaque[i] = opaque;
252 /* size is the word size in byte */
253 int register_ioport_write(int start, int length, int size,
254 IOPortWriteFunc *func, void *opaque)
260 } else if (size == 2) {
262 } else if (size == 4) {
265 hw_error("register_ioport_write: invalid size");
268 for(i = start; i < start + length; i += size) {
269 ioport_write_table[bsize][i] = func;
270 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
271 hw_error("register_ioport_read: invalid opaque");
272 ioport_opaque[i] = opaque;
277 void isa_unassign_ioport(int start, int length)
281 for(i = start; i < start + length; i++) {
282 ioport_read_table[0][i] = default_ioport_readb;
283 ioport_read_table[1][i] = default_ioport_readw;
284 ioport_read_table[2][i] = default_ioport_readl;
286 ioport_write_table[0][i] = default_ioport_writeb;
287 ioport_write_table[1][i] = default_ioport_writew;
288 ioport_write_table[2][i] = default_ioport_writel;
292 /***********************************************************/
294 void pstrcpy(char *buf, int buf_size, const char *str)
304 if (c == 0 || q >= buf + buf_size - 1)
311 /* strcat and truncate. */
312 char *pstrcat(char *buf, int buf_size, const char *s)
317 pstrcpy(buf + len, buf_size - len, s);
321 int strstart(const char *str, const char *val, const char **ptr)
337 void cpu_outb(CPUState *env, int addr, int val)
340 if (loglevel & CPU_LOG_IOPORT)
341 fprintf(logfile, "outb: %04x %02x\n", addr, val);
343 ioport_write_table[0][addr](ioport_opaque[addr], addr, val);
346 env->last_io_time = cpu_get_time_fast();
350 void cpu_outw(CPUState *env, int addr, int val)
353 if (loglevel & CPU_LOG_IOPORT)
354 fprintf(logfile, "outw: %04x %04x\n", addr, val);
356 ioport_write_table[1][addr](ioport_opaque[addr], addr, val);
359 env->last_io_time = cpu_get_time_fast();
363 void cpu_outl(CPUState *env, int addr, int val)
366 if (loglevel & CPU_LOG_IOPORT)
367 fprintf(logfile, "outl: %04x %08x\n", addr, val);
369 ioport_write_table[2][addr](ioport_opaque[addr], addr, val);
372 env->last_io_time = cpu_get_time_fast();
376 int cpu_inb(CPUState *env, int addr)
379 val = ioport_read_table[0][addr](ioport_opaque[addr], addr);
381 if (loglevel & CPU_LOG_IOPORT)
382 fprintf(logfile, "inb : %04x %02x\n", addr, val);
386 env->last_io_time = cpu_get_time_fast();
391 int cpu_inw(CPUState *env, int addr)
394 val = ioport_read_table[1][addr](ioport_opaque[addr], addr);
396 if (loglevel & CPU_LOG_IOPORT)
397 fprintf(logfile, "inw : %04x %04x\n", addr, val);
401 env->last_io_time = cpu_get_time_fast();
406 int cpu_inl(CPUState *env, int addr)
409 val = ioport_read_table[2][addr](ioport_opaque[addr], addr);
411 if (loglevel & CPU_LOG_IOPORT)
412 fprintf(logfile, "inl : %04x %08x\n", addr, val);
416 env->last_io_time = cpu_get_time_fast();
421 /***********************************************************/
422 void hw_error(const char *fmt, ...)
428 fprintf(stderr, "qemu: hardware error: ");
429 vfprintf(stderr, fmt, ap);
430 fprintf(stderr, "\n");
431 for(env = first_cpu; env != NULL; env = env->next_cpu) {
432 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
434 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
436 cpu_dump_state(env, stderr, fprintf, 0);
443 /***********************************************************/
446 static QEMUPutKBDEvent *qemu_put_kbd_event;
447 static void *qemu_put_kbd_event_opaque;
448 static QEMUPutMouseEvent *qemu_put_mouse_event;
449 static void *qemu_put_mouse_event_opaque;
450 static int qemu_put_mouse_event_absolute;
452 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
454 qemu_put_kbd_event_opaque = opaque;
455 qemu_put_kbd_event = func;
458 void qemu_add_mouse_event_handler(QEMUPutMouseEvent *func, void *opaque, int absolute)
460 qemu_put_mouse_event_opaque = opaque;
461 qemu_put_mouse_event = func;
462 qemu_put_mouse_event_absolute = absolute;
465 void kbd_put_keycode(int keycode)
467 if (qemu_put_kbd_event) {
468 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
472 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
474 if (qemu_put_mouse_event) {
475 qemu_put_mouse_event(qemu_put_mouse_event_opaque,
476 dx, dy, dz, buttons_state);
480 int kbd_mouse_is_absolute(void)
482 return qemu_put_mouse_event_absolute;
485 /***********************************************************/
488 #if defined(__powerpc__)
490 static inline uint32_t get_tbl(void)
493 asm volatile("mftb %0" : "=r" (tbl));
497 static inline uint32_t get_tbu(void)
500 asm volatile("mftbu %0" : "=r" (tbl));
504 int64_t cpu_get_real_ticks(void)
507 /* NOTE: we test if wrapping has occurred */
513 return ((int64_t)h << 32) | l;
516 #elif defined(__i386__)
518 int64_t cpu_get_real_ticks(void)
521 asm volatile ("rdtsc" : "=A" (val));
525 #elif defined(__x86_64__)
527 int64_t cpu_get_real_ticks(void)
531 asm volatile("rdtsc" : "=a" (low), "=d" (high));
538 #elif defined(__ia64)
540 int64_t cpu_get_real_ticks(void)
543 asm volatile ("mov %0 = ar.itc" : "=r"(val) :: "memory");
547 #elif defined(__s390__)
549 int64_t cpu_get_real_ticks(void)
552 asm volatile("stck 0(%1)" : "=m" (val) : "a" (&val) : "cc");
557 #error unsupported CPU
560 static int64_t cpu_ticks_offset;
561 static int cpu_ticks_enabled;
563 static inline int64_t cpu_get_ticks(void)
565 if (!cpu_ticks_enabled) {
566 return cpu_ticks_offset;
568 return cpu_get_real_ticks() + cpu_ticks_offset;
572 /* enable cpu_get_ticks() */
573 void cpu_enable_ticks(void)
575 if (!cpu_ticks_enabled) {
576 cpu_ticks_offset -= cpu_get_real_ticks();
577 cpu_ticks_enabled = 1;
581 /* disable cpu_get_ticks() : the clock is stopped. You must not call
582 cpu_get_ticks() after that. */
583 void cpu_disable_ticks(void)
585 if (cpu_ticks_enabled) {
586 cpu_ticks_offset = cpu_get_ticks();
587 cpu_ticks_enabled = 0;
591 static int64_t get_clock(void)
596 return ((int64_t)tb.time * 1000 + (int64_t)tb.millitm) * 1000;
599 gettimeofday(&tv, NULL);
600 return tv.tv_sec * 1000000LL + tv.tv_usec;
604 void cpu_calibrate_ticks(void)
609 ticks = cpu_get_real_ticks();
615 usec = get_clock() - usec;
616 ticks = cpu_get_real_ticks() - ticks;
617 ticks_per_sec = (ticks * 1000000LL + (usec >> 1)) / usec;
620 /* compute with 96 bit intermediate result: (a*b)/c */
621 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
626 #ifdef WORDS_BIGENDIAN
636 rl = (uint64_t)u.l.low * (uint64_t)b;
637 rh = (uint64_t)u.l.high * (uint64_t)b;
640 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
644 #define QEMU_TIMER_REALTIME 0
645 #define QEMU_TIMER_VIRTUAL 1
649 /* XXX: add frequency */
657 struct QEMUTimer *next;
663 static QEMUTimer *active_timers[2];
665 static MMRESULT timerID;
667 /* frequency of the times() clock tick */
668 static int timer_freq;
671 QEMUClock *qemu_new_clock(int type)
674 clock = qemu_mallocz(sizeof(QEMUClock));
681 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
685 ts = qemu_mallocz(sizeof(QEMUTimer));
692 void qemu_free_timer(QEMUTimer *ts)
697 /* stop a timer, but do not dealloc it */
698 void qemu_del_timer(QEMUTimer *ts)
702 /* NOTE: this code must be signal safe because
703 qemu_timer_expired() can be called from a signal. */
704 pt = &active_timers[ts->clock->type];
717 /* modify the current timer so that it will be fired when current_time
718 >= expire_time. The corresponding callback will be called. */
719 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
725 /* add the timer in the sorted list */
726 /* NOTE: this code must be signal safe because
727 qemu_timer_expired() can be called from a signal. */
728 pt = &active_timers[ts->clock->type];
733 if (t->expire_time > expire_time)
737 ts->expire_time = expire_time;
742 int qemu_timer_pending(QEMUTimer *ts)
745 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
752 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
756 return (timer_head->expire_time <= current_time);
759 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
765 if (!ts || ts->expire_time > current_time)
767 /* remove timer from the list before calling the callback */
768 *ptimer_head = ts->next;
771 /* run the callback (the timer list can be modified) */
776 int64_t qemu_get_clock(QEMUClock *clock)
778 switch(clock->type) {
779 case QEMU_TIMER_REALTIME:
781 return GetTickCount();
786 /* Note that using gettimeofday() is not a good solution
787 for timers because its value change when the date is
789 if (timer_freq == 100) {
790 return times(&tp) * 10;
792 return ((int64_t)times(&tp) * 1000) / timer_freq;
797 case QEMU_TIMER_VIRTUAL:
798 return cpu_get_ticks();
803 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
805 uint64_t expire_time;
807 if (qemu_timer_pending(ts)) {
808 expire_time = ts->expire_time;
812 qemu_put_be64(f, expire_time);
815 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
817 uint64_t expire_time;
819 expire_time = qemu_get_be64(f);
820 if (expire_time != -1) {
821 qemu_mod_timer(ts, expire_time);
827 static void timer_save(QEMUFile *f, void *opaque)
829 if (cpu_ticks_enabled) {
830 hw_error("cannot save state if virtual timers are running");
832 qemu_put_be64s(f, &cpu_ticks_offset);
833 qemu_put_be64s(f, &ticks_per_sec);
836 static int timer_load(QEMUFile *f, void *opaque, int version_id)
840 if (cpu_ticks_enabled) {
843 qemu_get_be64s(f, &cpu_ticks_offset);
844 qemu_get_be64s(f, &ticks_per_sec);
849 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
850 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
852 static void host_alarm_handler(int host_signum)
856 #define DISP_FREQ 1000
858 static int64_t delta_min = INT64_MAX;
859 static int64_t delta_max, delta_cum, last_clock, delta, ti;
861 ti = qemu_get_clock(vm_clock);
862 if (last_clock != 0) {
863 delta = ti - last_clock;
864 if (delta < delta_min)
866 if (delta > delta_max)
869 if (++count == DISP_FREQ) {
870 printf("timer: min=%lld us max=%lld us avg=%lld us avg_freq=%0.3f Hz\n",
871 muldiv64(delta_min, 1000000, ticks_per_sec),
872 muldiv64(delta_max, 1000000, ticks_per_sec),
873 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
874 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
876 delta_min = INT64_MAX;
884 if (qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
885 qemu_get_clock(vm_clock)) ||
886 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
887 qemu_get_clock(rt_clock))) {
888 CPUState *env = cpu_single_env;
890 /* stop the currently executing cpu because a timer occured */
891 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
893 if (env->kqemu_enabled) {
894 kqemu_cpu_interrupt(env);
903 #if defined(__linux__)
905 #define RTC_FREQ 1024
909 static int start_rtc_timer(void)
911 rtc_fd = open("/dev/rtc", O_RDONLY);
914 if (ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
915 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
916 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
917 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
920 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
925 pit_min_timer_count = PIT_FREQ / RTC_FREQ;
931 static int start_rtc_timer(void)
936 #endif /* !defined(__linux__) */
938 #endif /* !defined(_WIN32) */
940 static void init_timers(void)
942 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
943 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
948 timerID = timeSetEvent(1, // interval (ms)
950 host_alarm_handler, // function
951 (DWORD)&count, // user parameter
952 TIME_PERIODIC | TIME_CALLBACK_FUNCTION);
954 perror("failed timer alarm");
958 pit_min_timer_count = ((uint64_t)10000 * PIT_FREQ) / 1000000;
961 struct sigaction act;
962 struct itimerval itv;
964 /* get times() syscall frequency */
965 timer_freq = sysconf(_SC_CLK_TCK);
968 sigfillset(&act.sa_mask);
970 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
971 act.sa_flags |= SA_ONSTACK;
973 act.sa_handler = host_alarm_handler;
974 sigaction(SIGALRM, &act, NULL);
976 itv.it_interval.tv_sec = 0;
977 itv.it_interval.tv_usec = 999; /* for i386 kernel 2.6 to get 1 ms */
978 itv.it_value.tv_sec = 0;
979 itv.it_value.tv_usec = 10 * 1000;
980 setitimer(ITIMER_REAL, &itv, NULL);
981 /* we probe the tick duration of the kernel to inform the user if
982 the emulated kernel requested a too high timer frequency */
983 getitimer(ITIMER_REAL, &itv);
985 #if defined(__linux__)
986 if (itv.it_interval.tv_usec > 1000) {
987 /* try to use /dev/rtc to have a faster timer */
988 if (start_rtc_timer() < 0)
991 itv.it_interval.tv_sec = 0;
992 itv.it_interval.tv_usec = 0;
993 itv.it_value.tv_sec = 0;
994 itv.it_value.tv_usec = 0;
995 setitimer(ITIMER_REAL, &itv, NULL);
998 sigaction(SIGIO, &act, NULL);
999 fcntl(rtc_fd, F_SETFL, O_ASYNC);
1000 fcntl(rtc_fd, F_SETOWN, getpid());
1002 #endif /* defined(__linux__) */
1005 pit_min_timer_count = ((uint64_t)itv.it_interval.tv_usec *
1006 PIT_FREQ) / 1000000;
1012 void quit_timers(void)
1015 timeKillEvent(timerID);
1019 /***********************************************************/
1020 /* character device */
1022 int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1024 return s->chr_write(s, buf, len);
1027 int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1031 return s->chr_ioctl(s, cmd, arg);
1034 void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1039 vsnprintf(buf, sizeof(buf), fmt, ap);
1040 qemu_chr_write(s, buf, strlen(buf));
1044 void qemu_chr_send_event(CharDriverState *s, int event)
1046 if (s->chr_send_event)
1047 s->chr_send_event(s, event);
1050 void qemu_chr_add_read_handler(CharDriverState *s,
1051 IOCanRWHandler *fd_can_read,
1052 IOReadHandler *fd_read, void *opaque)
1054 s->chr_add_read_handler(s, fd_can_read, fd_read, opaque);
1057 void qemu_chr_add_event_handler(CharDriverState *s, IOEventHandler *chr_event)
1059 s->chr_event = chr_event;
1062 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1067 static void null_chr_add_read_handler(CharDriverState *chr,
1068 IOCanRWHandler *fd_can_read,
1069 IOReadHandler *fd_read, void *opaque)
1073 CharDriverState *qemu_chr_open_null(void)
1075 CharDriverState *chr;
1077 chr = qemu_mallocz(sizeof(CharDriverState));
1080 chr->chr_write = null_chr_write;
1081 chr->chr_add_read_handler = null_chr_add_read_handler;
1087 #define socket_error() WSAGetLastError()
1089 #define EWOULDBLOCK WSAEWOULDBLOCK
1090 #define EINTR WSAEINTR
1091 #define EINPROGRESS WSAEINPROGRESS
1093 static void socket_cleanup(void)
1098 static int socket_init(void)
1103 ret = WSAStartup(MAKEWORD(2,2), &Data);
1105 err = WSAGetLastError();
1106 fprintf(stderr, "WSAStartup: %d\n", err);
1109 atexit(socket_cleanup);
1113 static int send_all(int fd, const uint8_t *buf, int len1)
1119 ret = send(fd, buf, len, 0);
1122 errno = WSAGetLastError();
1123 if (errno != WSAEWOULDBLOCK) {
1126 } else if (ret == 0) {
1136 void socket_set_nonblock(int fd)
1138 unsigned long opt = 1;
1139 ioctlsocket(fd, FIONBIO, &opt);
1144 #define socket_error() errno
1145 #define closesocket(s) close(s)
1147 static int unix_write(int fd, const uint8_t *buf, int len1)
1153 ret = write(fd, buf, len);
1155 if (errno != EINTR && errno != EAGAIN)
1157 } else if (ret == 0) {
1167 static inline int send_all(int fd, const uint8_t *buf, int len1)
1169 return unix_write(fd, buf, len1);
1172 void socket_set_nonblock(int fd)
1174 fcntl(fd, F_SETFL, O_NONBLOCK);
1176 #endif /* !_WIN32 */
1182 IOCanRWHandler *fd_can_read;
1183 IOReadHandler *fd_read;
1188 #define STDIO_MAX_CLIENTS 2
1190 static int stdio_nb_clients;
1191 static CharDriverState *stdio_clients[STDIO_MAX_CLIENTS];
1193 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1195 FDCharDriver *s = chr->opaque;
1196 return unix_write(s->fd_out, buf, len);
1199 static int fd_chr_read_poll(void *opaque)
1201 CharDriverState *chr = opaque;
1202 FDCharDriver *s = chr->opaque;
1204 s->max_size = s->fd_can_read(s->fd_opaque);
1208 static void fd_chr_read(void *opaque)
1210 CharDriverState *chr = opaque;
1211 FDCharDriver *s = chr->opaque;
1216 if (len > s->max_size)
1220 size = read(s->fd_in, buf, len);
1222 s->fd_read(s->fd_opaque, buf, size);
1226 static void fd_chr_add_read_handler(CharDriverState *chr,
1227 IOCanRWHandler *fd_can_read,
1228 IOReadHandler *fd_read, void *opaque)
1230 FDCharDriver *s = chr->opaque;
1232 if (s->fd_in >= 0) {
1233 s->fd_can_read = fd_can_read;
1234 s->fd_read = fd_read;
1235 s->fd_opaque = opaque;
1236 if (nographic && s->fd_in == 0) {
1238 qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
1239 fd_chr_read, NULL, chr);
1244 /* open a character device to a unix fd */
1245 CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
1247 CharDriverState *chr;
1250 chr = qemu_mallocz(sizeof(CharDriverState));
1253 s = qemu_mallocz(sizeof(FDCharDriver));
1261 chr->chr_write = fd_chr_write;
1262 chr->chr_add_read_handler = fd_chr_add_read_handler;
1266 CharDriverState *qemu_chr_open_file_out(const char *file_out)
1270 fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666);
1273 return qemu_chr_open_fd(-1, fd_out);
1276 CharDriverState *qemu_chr_open_pipe(const char *filename)
1280 fd = open(filename, O_RDWR | O_BINARY);
1283 return qemu_chr_open_fd(fd, fd);
1287 /* for STDIO, we handle the case where several clients use it
1290 #define TERM_ESCAPE 0x01 /* ctrl-a is used for escape */
1292 #define TERM_FIFO_MAX_SIZE 1
1294 static int term_got_escape, client_index;
1295 static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
1298 void term_print_help(void)
1301 "C-a h print this help\n"
1302 "C-a x exit emulator\n"
1303 "C-a s save disk data back to file (if -snapshot)\n"
1304 "C-a b send break (magic sysrq)\n"
1305 "C-a c switch between console and monitor\n"
1306 "C-a C-a send C-a\n"
1310 /* called when a char is received */
1311 static void stdio_received_byte(int ch)
1313 if (term_got_escape) {
1314 term_got_escape = 0;
1325 for (i = 0; i < MAX_DISKS; i++) {
1327 bdrv_commit(bs_table[i]);
1332 if (client_index < stdio_nb_clients) {
1333 CharDriverState *chr;
1336 chr = stdio_clients[client_index];
1338 chr->chr_event(s->fd_opaque, CHR_EVENT_BREAK);
1343 if (client_index >= stdio_nb_clients)
1345 if (client_index == 0) {
1346 /* send a new line in the monitor to get the prompt */
1354 } else if (ch == TERM_ESCAPE) {
1355 term_got_escape = 1;
1358 if (client_index < stdio_nb_clients) {
1360 CharDriverState *chr;
1363 chr = stdio_clients[client_index];
1365 if (s->fd_can_read(s->fd_opaque) > 0) {
1367 s->fd_read(s->fd_opaque, buf, 1);
1368 } else if (term_fifo_size == 0) {
1369 term_fifo[term_fifo_size++] = ch;
1375 static int stdio_read_poll(void *opaque)
1377 CharDriverState *chr;
1380 if (client_index < stdio_nb_clients) {
1381 chr = stdio_clients[client_index];
1383 /* try to flush the queue if needed */
1384 if (term_fifo_size != 0 && s->fd_can_read(s->fd_opaque) > 0) {
1385 s->fd_read(s->fd_opaque, term_fifo, 1);
1388 /* see if we can absorb more chars */
1389 if (term_fifo_size == 0)
1398 static void stdio_read(void *opaque)
1403 size = read(0, buf, 1);
1405 stdio_received_byte(buf[0]);
1408 /* init terminal so that we can grab keys */
1409 static struct termios oldtty;
1410 static int old_fd0_flags;
1412 static void term_exit(void)
1414 tcsetattr (0, TCSANOW, &oldtty);
1415 fcntl(0, F_SETFL, old_fd0_flags);
1418 static void term_init(void)
1422 tcgetattr (0, &tty);
1424 old_fd0_flags = fcntl(0, F_GETFL);
1426 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1427 |INLCR|IGNCR|ICRNL|IXON);
1428 tty.c_oflag |= OPOST;
1429 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1430 /* if graphical mode, we allow Ctrl-C handling */
1432 tty.c_lflag &= ~ISIG;
1433 tty.c_cflag &= ~(CSIZE|PARENB);
1436 tty.c_cc[VTIME] = 0;
1438 tcsetattr (0, TCSANOW, &tty);
1442 fcntl(0, F_SETFL, O_NONBLOCK);
1445 CharDriverState *qemu_chr_open_stdio(void)
1447 CharDriverState *chr;
1450 if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
1452 chr = qemu_chr_open_fd(0, 1);
1453 if (stdio_nb_clients == 0)
1454 qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, NULL);
1455 client_index = stdio_nb_clients;
1457 if (stdio_nb_clients != 0)
1459 chr = qemu_chr_open_fd(0, 1);
1461 stdio_clients[stdio_nb_clients++] = chr;
1462 if (stdio_nb_clients == 1) {
1463 /* set the terminal in raw mode */
1469 #if defined(__linux__)
1470 CharDriverState *qemu_chr_open_pty(void)
1473 char slave_name[1024];
1474 int master_fd, slave_fd;
1476 /* Not satisfying */
1477 if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
1481 /* Disabling local echo and line-buffered output */
1482 tcgetattr (master_fd, &tty);
1483 tty.c_lflag &= ~(ECHO|ICANON|ISIG);
1485 tty.c_cc[VTIME] = 0;
1486 tcsetattr (master_fd, TCSAFLUSH, &tty);
1488 fprintf(stderr, "char device redirected to %s\n", slave_name);
1489 return qemu_chr_open_fd(master_fd, master_fd);
1492 static void tty_serial_init(int fd, int speed,
1493 int parity, int data_bits, int stop_bits)
1499 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1500 speed, parity, data_bits, stop_bits);
1502 tcgetattr (fd, &tty);
1544 cfsetispeed(&tty, spd);
1545 cfsetospeed(&tty, spd);
1547 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1548 |INLCR|IGNCR|ICRNL|IXON);
1549 tty.c_oflag |= OPOST;
1550 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1551 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS);
1572 tty.c_cflag |= PARENB;
1575 tty.c_cflag |= PARENB | PARODD;
1579 tcsetattr (fd, TCSANOW, &tty);
1582 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1584 FDCharDriver *s = chr->opaque;
1587 case CHR_IOCTL_SERIAL_SET_PARAMS:
1589 QEMUSerialSetParams *ssp = arg;
1590 tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
1591 ssp->data_bits, ssp->stop_bits);
1594 case CHR_IOCTL_SERIAL_SET_BREAK:
1596 int enable = *(int *)arg;
1598 tcsendbreak(s->fd_in, 1);
1607 CharDriverState *qemu_chr_open_tty(const char *filename)
1609 CharDriverState *chr;
1612 fd = open(filename, O_RDWR | O_NONBLOCK);
1615 fcntl(fd, F_SETFL, O_NONBLOCK);
1616 tty_serial_init(fd, 115200, 'N', 8, 1);
1617 chr = qemu_chr_open_fd(fd, fd);
1620 chr->chr_ioctl = tty_serial_ioctl;
1624 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1626 int fd = (int)chr->opaque;
1630 case CHR_IOCTL_PP_READ_DATA:
1631 if (ioctl(fd, PPRDATA, &b) < 0)
1633 *(uint8_t *)arg = b;
1635 case CHR_IOCTL_PP_WRITE_DATA:
1636 b = *(uint8_t *)arg;
1637 if (ioctl(fd, PPWDATA, &b) < 0)
1640 case CHR_IOCTL_PP_READ_CONTROL:
1641 if (ioctl(fd, PPRCONTROL, &b) < 0)
1643 *(uint8_t *)arg = b;
1645 case CHR_IOCTL_PP_WRITE_CONTROL:
1646 b = *(uint8_t *)arg;
1647 if (ioctl(fd, PPWCONTROL, &b) < 0)
1650 case CHR_IOCTL_PP_READ_STATUS:
1651 if (ioctl(fd, PPRSTATUS, &b) < 0)
1653 *(uint8_t *)arg = b;
1661 CharDriverState *qemu_chr_open_pp(const char *filename)
1663 CharDriverState *chr;
1666 fd = open(filename, O_RDWR);
1670 if (ioctl(fd, PPCLAIM) < 0) {
1675 chr = qemu_mallocz(sizeof(CharDriverState));
1680 chr->opaque = (void *)fd;
1681 chr->chr_write = null_chr_write;
1682 chr->chr_add_read_handler = null_chr_add_read_handler;
1683 chr->chr_ioctl = pp_ioctl;
1688 CharDriverState *qemu_chr_open_pty(void)
1694 #endif /* !defined(_WIN32) */
1698 IOCanRWHandler *fd_can_read;
1699 IOReadHandler *fd_read;
1702 HANDLE hcom, hrecv, hsend;
1703 OVERLAPPED orecv, osend;
1708 #define NSENDBUF 2048
1709 #define NRECVBUF 2048
1710 #define MAXCONNECT 1
1711 #define NTIMEOUT 5000
1713 static int win_chr_poll(void *opaque);
1714 static int win_chr_pipe_poll(void *opaque);
1716 static void win_chr_close2(WinCharState *s)
1719 CloseHandle(s->hsend);
1723 CloseHandle(s->hrecv);
1727 CloseHandle(s->hcom);
1731 qemu_del_polling_cb(win_chr_pipe_poll, s);
1733 qemu_del_polling_cb(win_chr_poll, s);
1736 static void win_chr_close(CharDriverState *chr)
1738 WinCharState *s = chr->opaque;
1742 static int win_chr_init(WinCharState *s, const char *filename)
1745 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
1750 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1752 fprintf(stderr, "Failed CreateEvent\n");
1755 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1757 fprintf(stderr, "Failed CreateEvent\n");
1761 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
1762 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
1763 if (s->hcom == INVALID_HANDLE_VALUE) {
1764 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
1769 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
1770 fprintf(stderr, "Failed SetupComm\n");
1774 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
1775 size = sizeof(COMMCONFIG);
1776 GetDefaultCommConfig(filename, &comcfg, &size);
1777 comcfg.dcb.DCBlength = sizeof(DCB);
1778 CommConfigDialog(filename, NULL, &comcfg);
1780 if (!SetCommState(s->hcom, &comcfg.dcb)) {
1781 fprintf(stderr, "Failed SetCommState\n");
1785 if (!SetCommMask(s->hcom, EV_ERR)) {
1786 fprintf(stderr, "Failed SetCommMask\n");
1790 cto.ReadIntervalTimeout = MAXDWORD;
1791 if (!SetCommTimeouts(s->hcom, &cto)) {
1792 fprintf(stderr, "Failed SetCommTimeouts\n");
1796 if (!ClearCommError(s->hcom, &err, &comstat)) {
1797 fprintf(stderr, "Failed ClearCommError\n");
1800 qemu_add_polling_cb(win_chr_poll, s);
1808 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
1810 WinCharState *s = chr->opaque;
1811 DWORD len, ret, size, err;
1814 ZeroMemory(&s->osend, sizeof(s->osend));
1815 s->osend.hEvent = s->hsend;
1818 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
1820 ret = WriteFile(s->hcom, buf, len, &size, NULL);
1822 err = GetLastError();
1823 if (err == ERROR_IO_PENDING) {
1824 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
1842 static int win_chr_read_poll(WinCharState *s)
1844 s->max_size = s->fd_can_read(s->win_opaque);
1848 static void win_chr_readfile(WinCharState *s)
1854 ZeroMemory(&s->orecv, sizeof(s->orecv));
1855 s->orecv.hEvent = s->hrecv;
1856 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
1858 err = GetLastError();
1859 if (err == ERROR_IO_PENDING) {
1860 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
1865 s->fd_read(s->win_opaque, buf, size);
1869 static void win_chr_read(WinCharState *s)
1871 if (s->len > s->max_size)
1872 s->len = s->max_size;
1876 win_chr_readfile(s);
1879 static int win_chr_poll(void *opaque)
1881 WinCharState *s = opaque;
1885 ClearCommError(s->hcom, &comerr, &status);
1886 if (status.cbInQue > 0) {
1887 s->len = status.cbInQue;
1888 win_chr_read_poll(s);
1895 static void win_chr_add_read_handler(CharDriverState *chr,
1896 IOCanRWHandler *fd_can_read,
1897 IOReadHandler *fd_read, void *opaque)
1899 WinCharState *s = chr->opaque;
1901 s->fd_can_read = fd_can_read;
1902 s->fd_read = fd_read;
1903 s->win_opaque = opaque;
1906 CharDriverState *qemu_chr_open_win(const char *filename)
1908 CharDriverState *chr;
1911 chr = qemu_mallocz(sizeof(CharDriverState));
1914 s = qemu_mallocz(sizeof(WinCharState));
1920 chr->chr_write = win_chr_write;
1921 chr->chr_add_read_handler = win_chr_add_read_handler;
1922 chr->chr_close = win_chr_close;
1924 if (win_chr_init(s, filename) < 0) {
1932 static int win_chr_pipe_poll(void *opaque)
1934 WinCharState *s = opaque;
1937 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
1940 win_chr_read_poll(s);
1947 static int win_chr_pipe_init(WinCharState *s, const char *filename)
1956 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1958 fprintf(stderr, "Failed CreateEvent\n");
1961 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1963 fprintf(stderr, "Failed CreateEvent\n");
1967 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
1968 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
1969 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
1971 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
1972 if (s->hcom == INVALID_HANDLE_VALUE) {
1973 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
1978 ZeroMemory(&ov, sizeof(ov));
1979 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
1980 ret = ConnectNamedPipe(s->hcom, &ov);
1982 fprintf(stderr, "Failed ConnectNamedPipe\n");
1986 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
1988 fprintf(stderr, "Failed GetOverlappedResult\n");
1990 CloseHandle(ov.hEvent);
1997 CloseHandle(ov.hEvent);
2000 qemu_add_polling_cb(win_chr_pipe_poll, s);
2009 CharDriverState *qemu_chr_open_win_pipe(const char *filename)
2011 CharDriverState *chr;
2014 chr = qemu_mallocz(sizeof(CharDriverState));
2017 s = qemu_mallocz(sizeof(WinCharState));
2023 chr->chr_write = win_chr_write;
2024 chr->chr_add_read_handler = win_chr_add_read_handler;
2025 chr->chr_close = win_chr_close;
2027 if (win_chr_pipe_init(s, filename) < 0) {
2035 CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
2037 CharDriverState *chr;
2040 chr = qemu_mallocz(sizeof(CharDriverState));
2043 s = qemu_mallocz(sizeof(WinCharState));
2050 chr->chr_write = win_chr_write;
2051 chr->chr_add_read_handler = win_chr_add_read_handler;
2055 CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
2059 fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
2060 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2061 if (fd_out == INVALID_HANDLE_VALUE)
2064 return qemu_chr_open_win_file(fd_out);
2068 CharDriverState *qemu_chr_open(const char *filename)
2072 if (!strcmp(filename, "vc")) {
2073 return text_console_init(&display_state);
2074 } else if (!strcmp(filename, "null")) {
2075 return qemu_chr_open_null();
2078 if (strstart(filename, "file:", &p)) {
2079 return qemu_chr_open_file_out(p);
2080 } else if (strstart(filename, "pipe:", &p)) {
2081 return qemu_chr_open_pipe(p);
2082 } else if (!strcmp(filename, "pty")) {
2083 return qemu_chr_open_pty();
2084 } else if (!strcmp(filename, "stdio")) {
2085 return qemu_chr_open_stdio();
2088 #if defined(__linux__)
2089 if (strstart(filename, "/dev/parport", NULL)) {
2090 return qemu_chr_open_pp(filename);
2092 if (strstart(filename, "/dev/", NULL)) {
2093 return qemu_chr_open_tty(filename);
2097 if (strstart(filename, "COM", NULL)) {
2098 return qemu_chr_open_win(filename);
2100 if (strstart(filename, "pipe:", &p)) {
2101 return qemu_chr_open_win_pipe(p);
2103 if (strstart(filename, "file:", &p)) {
2104 return qemu_chr_open_win_file_out(p);
2112 void qemu_chr_close(CharDriverState *chr)
2115 chr->chr_close(chr);
2118 /***********************************************************/
2119 /* network device redirectors */
2121 void hex_dump(FILE *f, const uint8_t *buf, int size)
2125 for(i=0;i<size;i+=16) {
2129 fprintf(f, "%08x ", i);
2132 fprintf(f, " %02x", buf[i+j]);
2137 for(j=0;j<len;j++) {
2139 if (c < ' ' || c > '~')
2141 fprintf(f, "%c", c);
2147 static int parse_macaddr(uint8_t *macaddr, const char *p)
2150 for(i = 0; i < 6; i++) {
2151 macaddr[i] = strtol(p, (char **)&p, 16);
2164 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
2169 p1 = strchr(p, sep);
2175 if (len > buf_size - 1)
2177 memcpy(buf, p, len);
2184 int parse_host_port(struct sockaddr_in *saddr, const char *str)
2192 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2194 saddr->sin_family = AF_INET;
2195 if (buf[0] == '\0') {
2196 saddr->sin_addr.s_addr = 0;
2198 if (isdigit(buf[0])) {
2199 if (!inet_aton(buf, &saddr->sin_addr))
2202 if ((he = gethostbyname(buf)) == NULL)
2204 saddr->sin_addr = *(struct in_addr *)he->h_addr;
2207 port = strtol(p, (char **)&r, 0);
2210 saddr->sin_port = htons(port);
2214 /* find or alloc a new VLAN */
2215 VLANState *qemu_find_vlan(int id)
2217 VLANState **pvlan, *vlan;
2218 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
2222 vlan = qemu_mallocz(sizeof(VLANState));
2227 pvlan = &first_vlan;
2228 while (*pvlan != NULL)
2229 pvlan = &(*pvlan)->next;
2234 VLANClientState *qemu_new_vlan_client(VLANState *vlan,
2235 IOReadHandler *fd_read,
2236 IOCanRWHandler *fd_can_read,
2239 VLANClientState *vc, **pvc;
2240 vc = qemu_mallocz(sizeof(VLANClientState));
2243 vc->fd_read = fd_read;
2244 vc->fd_can_read = fd_can_read;
2245 vc->opaque = opaque;
2249 pvc = &vlan->first_client;
2250 while (*pvc != NULL)
2251 pvc = &(*pvc)->next;
2256 int qemu_can_send_packet(VLANClientState *vc1)
2258 VLANState *vlan = vc1->vlan;
2259 VLANClientState *vc;
2261 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
2263 if (vc->fd_can_read && !vc->fd_can_read(vc->opaque))
2270 void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
2272 VLANState *vlan = vc1->vlan;
2273 VLANClientState *vc;
2276 printf("vlan %d send:\n", vlan->id);
2277 hex_dump(stdout, buf, size);
2279 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
2281 vc->fd_read(vc->opaque, buf, size);
2286 #if defined(CONFIG_SLIRP)
2288 /* slirp network adapter */
2290 static int slirp_inited;
2291 static VLANClientState *slirp_vc;
2293 int slirp_can_output(void)
2295 return !slirp_vc || qemu_can_send_packet(slirp_vc);
2298 void slirp_output(const uint8_t *pkt, int pkt_len)
2301 printf("slirp output:\n");
2302 hex_dump(stdout, pkt, pkt_len);
2306 qemu_send_packet(slirp_vc, pkt, pkt_len);
2309 static void slirp_receive(void *opaque, const uint8_t *buf, int size)
2312 printf("slirp input:\n");
2313 hex_dump(stdout, buf, size);
2315 slirp_input(buf, size);
2318 static int net_slirp_init(VLANState *vlan)
2320 if (!slirp_inited) {
2324 slirp_vc = qemu_new_vlan_client(vlan,
2325 slirp_receive, NULL, NULL);
2326 snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
2330 static void net_slirp_redir(const char *redir_str)
2335 struct in_addr guest_addr;
2336 int host_port, guest_port;
2338 if (!slirp_inited) {
2344 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2346 if (!strcmp(buf, "tcp")) {
2348 } else if (!strcmp(buf, "udp")) {
2354 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2356 host_port = strtol(buf, &r, 0);
2360 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2362 if (buf[0] == '\0') {
2363 pstrcpy(buf, sizeof(buf), "10.0.2.15");
2365 if (!inet_aton(buf, &guest_addr))
2368 guest_port = strtol(p, &r, 0);
2372 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
2373 fprintf(stderr, "qemu: could not set up redirection\n");
2378 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
2386 static void smb_exit(void)
2390 char filename[1024];
2392 /* erase all the files in the directory */
2393 d = opendir(smb_dir);
2398 if (strcmp(de->d_name, ".") != 0 &&
2399 strcmp(de->d_name, "..") != 0) {
2400 snprintf(filename, sizeof(filename), "%s/%s",
2401 smb_dir, de->d_name);
2409 /* automatic user mode samba server configuration */
2410 void net_slirp_smb(const char *exported_dir)
2412 char smb_conf[1024];
2413 char smb_cmdline[1024];
2416 if (!slirp_inited) {
2421 /* XXX: better tmp dir construction */
2422 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
2423 if (mkdir(smb_dir, 0700) < 0) {
2424 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
2427 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
2429 f = fopen(smb_conf, "w");
2431 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
2438 "socket address=127.0.0.1\n"
2439 "pid directory=%s\n"
2440 "lock directory=%s\n"
2441 "log file=%s/log.smbd\n"
2442 "smb passwd file=%s/smbpasswd\n"
2443 "security = share\n"
2458 snprintf(smb_cmdline, sizeof(smb_cmdline), "/usr/sbin/smbd -s %s",
2461 slirp_add_exec(0, smb_cmdline, 4, 139);
2464 #endif /* !defined(_WIN32) */
2466 #endif /* CONFIG_SLIRP */
2468 #if !defined(_WIN32)
2470 typedef struct TAPState {
2471 VLANClientState *vc;
2475 static void tap_receive(void *opaque, const uint8_t *buf, int size)
2477 TAPState *s = opaque;
2480 ret = write(s->fd, buf, size);
2481 if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
2488 static void tap_send(void *opaque)
2490 TAPState *s = opaque;
2494 size = read(s->fd, buf, sizeof(buf));
2496 qemu_send_packet(s->vc, buf, size);
2502 static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
2506 s = qemu_mallocz(sizeof(TAPState));
2510 s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
2511 qemu_set_fd_handler(s->fd, tap_send, NULL, s);
2512 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
2517 static int tap_open(char *ifname, int ifname_size)
2523 fd = open("/dev/tap", O_RDWR);
2525 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
2530 dev = devname(s.st_rdev, S_IFCHR);
2531 pstrcpy(ifname, ifname_size, dev);
2533 fcntl(fd, F_SETFL, O_NONBLOCK);
2536 #elif defined(__sun__)
2537 static int tap_open(char *ifname, int ifname_size)
2539 fprintf(stderr, "warning: tap_open not yet implemented\n");
2543 static int tap_open(char *ifname, int ifname_size)
2548 fd = open("/dev/net/tun", O_RDWR);
2550 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
2553 memset(&ifr, 0, sizeof(ifr));
2554 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
2555 if (ifname[0] != '\0')
2556 pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
2558 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
2559 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
2561 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
2565 pstrcpy(ifname, ifname_size, ifr.ifr_name);
2566 fcntl(fd, F_SETFL, O_NONBLOCK);
2571 static int net_tap_init(VLANState *vlan, const char *ifname1,
2572 const char *setup_script)
2575 int pid, status, fd;
2580 if (ifname1 != NULL)
2581 pstrcpy(ifname, sizeof(ifname), ifname1);
2584 fd = tap_open(ifname, sizeof(ifname));
2590 if (setup_script[0] != '\0') {
2591 /* try to launch network init script */
2596 *parg++ = (char *)setup_script;
2599 execv(setup_script, args);
2602 while (waitpid(pid, &status, 0) != pid);
2603 if (!WIFEXITED(status) ||
2604 WEXITSTATUS(status) != 0) {
2605 fprintf(stderr, "%s: could not launch network script\n",
2611 s = net_tap_fd_init(vlan, fd);
2614 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
2615 "tap: ifname=%s setup_script=%s", ifname, setup_script);
2619 #endif /* !_WIN32 */
2621 /* network connection */
2622 typedef struct NetSocketState {
2623 VLANClientState *vc;
2625 int state; /* 0 = getting length, 1 = getting data */
2629 struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
2632 typedef struct NetSocketListenState {
2635 } NetSocketListenState;
2637 /* XXX: we consider we can send the whole packet without blocking */
2638 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
2640 NetSocketState *s = opaque;
2644 send_all(s->fd, (const uint8_t *)&len, sizeof(len));
2645 send_all(s->fd, buf, size);
2648 static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
2650 NetSocketState *s = opaque;
2651 sendto(s->fd, buf, size, 0,
2652 (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
2655 static void net_socket_send(void *opaque)
2657 NetSocketState *s = opaque;
2662 size = recv(s->fd, buf1, sizeof(buf1), 0);
2664 err = socket_error();
2665 if (err != EWOULDBLOCK)
2667 } else if (size == 0) {
2668 /* end of connection */
2670 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2676 /* reassemble a packet from the network */
2682 memcpy(s->buf + s->index, buf, l);
2686 if (s->index == 4) {
2688 s->packet_len = ntohl(*(uint32_t *)s->buf);
2694 l = s->packet_len - s->index;
2697 memcpy(s->buf + s->index, buf, l);
2701 if (s->index >= s->packet_len) {
2702 qemu_send_packet(s->vc, s->buf, s->packet_len);
2711 static void net_socket_send_dgram(void *opaque)
2713 NetSocketState *s = opaque;
2716 size = recv(s->fd, s->buf, sizeof(s->buf), 0);
2720 /* end of connection */
2721 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2724 qemu_send_packet(s->vc, s->buf, size);
2727 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
2732 if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
2733 fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
2734 inet_ntoa(mcastaddr->sin_addr),
2735 (int)ntohl(mcastaddr->sin_addr.s_addr));
2739 fd = socket(PF_INET, SOCK_DGRAM, 0);
2741 perror("socket(PF_INET, SOCK_DGRAM)");
2746 ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
2747 (const char *)&val, sizeof(val));
2749 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
2753 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
2759 /* Add host to multicast group */
2760 imr.imr_multiaddr = mcastaddr->sin_addr;
2761 imr.imr_interface.s_addr = htonl(INADDR_ANY);
2763 ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
2764 (const char *)&imr, sizeof(struct ip_mreq));
2766 perror("setsockopt(IP_ADD_MEMBERSHIP)");
2770 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
2772 ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
2773 (const char *)&val, sizeof(val));
2775 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
2779 socket_set_nonblock(fd);
2782 if (fd>=0) close(fd);
2786 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd,
2789 struct sockaddr_in saddr;
2791 socklen_t saddr_len;
2794 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
2795 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
2796 * by ONLY ONE process: we must "clone" this dgram socket --jjo
2800 if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
2802 if (saddr.sin_addr.s_addr==0) {
2803 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
2807 /* clone dgram socket */
2808 newfd = net_socket_mcast_create(&saddr);
2810 /* error already reported by net_socket_mcast_create() */
2814 /* clone newfd to fd, close newfd */
2819 fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
2820 fd, strerror(errno));
2825 s = qemu_mallocz(sizeof(NetSocketState));
2830 s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
2831 qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
2833 /* mcast: save bound address as dst */
2834 if (is_connected) s->dgram_dst=saddr;
2836 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
2837 "socket: fd=%d (%s mcast=%s:%d)",
2838 fd, is_connected? "cloned" : "",
2839 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
2843 static void net_socket_connect(void *opaque)
2845 NetSocketState *s = opaque;
2846 qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
2849 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd,
2853 s = qemu_mallocz(sizeof(NetSocketState));
2857 s->vc = qemu_new_vlan_client(vlan,
2858 net_socket_receive, NULL, s);
2859 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
2860 "socket: fd=%d", fd);
2862 net_socket_connect(s);
2864 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
2869 static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
2872 int so_type=-1, optlen=sizeof(so_type);
2874 if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type, &optlen)< 0) {
2875 fprintf(stderr, "qemu: error: setsockopt(SO_TYPE) for fd=%d failed\n", fd);
2880 return net_socket_fd_init_dgram(vlan, fd, is_connected);
2882 return net_socket_fd_init_stream(vlan, fd, is_connected);
2884 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
2885 fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
2886 return net_socket_fd_init_stream(vlan, fd, is_connected);
2891 static void net_socket_accept(void *opaque)
2893 NetSocketListenState *s = opaque;
2895 struct sockaddr_in saddr;
2900 len = sizeof(saddr);
2901 fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
2902 if (fd < 0 && errno != EINTR) {
2904 } else if (fd >= 0) {
2908 s1 = net_socket_fd_init(s->vlan, fd, 1);
2912 snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
2913 "socket: connection from %s:%d",
2914 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
2918 static int net_socket_listen_init(VLANState *vlan, const char *host_str)
2920 NetSocketListenState *s;
2922 struct sockaddr_in saddr;
2924 if (parse_host_port(&saddr, host_str) < 0)
2927 s = qemu_mallocz(sizeof(NetSocketListenState));
2931 fd = socket(PF_INET, SOCK_STREAM, 0);
2936 socket_set_nonblock(fd);
2938 /* allow fast reuse */
2940 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
2942 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
2947 ret = listen(fd, 0);
2954 qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
2958 static int net_socket_connect_init(VLANState *vlan, const char *host_str)
2961 int fd, connected, ret, err;
2962 struct sockaddr_in saddr;
2964 if (parse_host_port(&saddr, host_str) < 0)
2967 fd = socket(PF_INET, SOCK_STREAM, 0);
2972 socket_set_nonblock(fd);
2976 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
2978 err = socket_error();
2979 if (err == EINTR || err == EWOULDBLOCK) {
2980 } else if (err == EINPROGRESS) {
2992 s = net_socket_fd_init(vlan, fd, connected);
2995 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
2996 "socket: connect to %s:%d",
2997 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3001 static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
3005 struct sockaddr_in saddr;
3007 if (parse_host_port(&saddr, host_str) < 0)
3011 fd = net_socket_mcast_create(&saddr);
3015 s = net_socket_fd_init(vlan, fd, 0);
3019 s->dgram_dst = saddr;
3021 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3022 "socket: mcast=%s:%d",
3023 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3028 static int get_param_value(char *buf, int buf_size,
3029 const char *tag, const char *str)
3038 while (*p != '\0' && *p != '=') {
3039 if ((q - option) < sizeof(option) - 1)
3047 if (!strcmp(tag, option)) {
3049 while (*p != '\0' && *p != ',') {
3050 if ((q - buf) < buf_size - 1)
3057 while (*p != '\0' && *p != ',') {
3068 int net_client_init(const char *str)
3079 while (*p != '\0' && *p != ',') {
3080 if ((q - device) < sizeof(device) - 1)
3088 if (get_param_value(buf, sizeof(buf), "vlan", p)) {
3089 vlan_id = strtol(buf, NULL, 0);
3091 vlan = qemu_find_vlan(vlan_id);
3093 fprintf(stderr, "Could not create vlan %d\n", vlan_id);
3096 if (!strcmp(device, "nic")) {
3100 if (nb_nics >= MAX_NICS) {
3101 fprintf(stderr, "Too Many NICs\n");
3104 nd = &nd_table[nb_nics];
3105 macaddr = nd->macaddr;
3111 macaddr[5] = 0x56 + nb_nics;
3113 if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
3114 if (parse_macaddr(macaddr, buf) < 0) {
3115 fprintf(stderr, "invalid syntax for ethernet address\n");
3119 if (get_param_value(buf, sizeof(buf), "model", p)) {
3120 nd->model = strdup(buf);
3126 if (!strcmp(device, "none")) {
3127 /* does nothing. It is needed to signal that no network cards
3132 if (!strcmp(device, "user")) {
3133 if (get_param_value(buf, sizeof(buf), "hostname", p)) {
3134 if (strlen(buf) > 32)
3136 strcpy(slirp_hostname, buf);
3138 ret = net_slirp_init(vlan);
3142 if (!strcmp(device, "tap")) {
3144 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
3145 fprintf(stderr, "tap: no interface name\n");
3148 ret = tap_win32_init(vlan, ifname);
3151 if (!strcmp(device, "tap")) {
3153 char setup_script[1024];
3155 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
3156 fd = strtol(buf, NULL, 0);
3158 if (net_tap_fd_init(vlan, fd))
3161 get_param_value(ifname, sizeof(ifname), "ifname", p);
3162 if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
3163 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
3165 ret = net_tap_init(vlan, ifname, setup_script);
3169 if (!strcmp(device, "socket")) {
3170 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
3172 fd = strtol(buf, NULL, 0);
3174 if (net_socket_fd_init(vlan, fd, 1))
3176 } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
3177 ret = net_socket_listen_init(vlan, buf);
3178 } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
3179 ret = net_socket_connect_init(vlan, buf);
3180 } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
3181 ret = net_socket_mcast_init(vlan, buf);
3183 fprintf(stderr, "Unknown socket options: %s\n", p);
3188 fprintf(stderr, "Unknown network device: %s\n", device);
3192 fprintf(stderr, "Could not initialize device '%s'\n", device);
3198 void do_info_network(void)
3201 VLANClientState *vc;
3203 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
3204 term_printf("VLAN %d devices:\n", vlan->id);
3205 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
3206 term_printf(" %s\n", vc->info_str);
3210 /***********************************************************/
3213 static int usb_device_add(const char *devname)
3221 for(i = 0;i < MAX_VM_USB_PORTS; i++) {
3222 if (!vm_usb_ports[i]->dev)
3225 if (i == MAX_VM_USB_PORTS)
3228 if (strstart(devname, "host:", &p)) {
3229 dev = usb_host_device_open(p);
3232 } else if (!strcmp(devname, "mouse")) {
3233 dev = usb_mouse_init();
3236 } else if (!strcmp(devname, "tablet")) {
3237 dev = usb_tablet_init();
3243 usb_attach(vm_usb_ports[i], dev);
3247 static int usb_device_del(const char *devname)
3250 int bus_num, addr, i;
3256 p = strchr(devname, '.');
3259 bus_num = strtoul(devname, NULL, 0);
3260 addr = strtoul(p + 1, NULL, 0);
3263 for(i = 0;i < MAX_VM_USB_PORTS; i++) {
3264 dev = vm_usb_ports[i]->dev;
3265 if (dev && dev->addr == addr)
3268 if (i == MAX_VM_USB_PORTS)
3270 usb_attach(vm_usb_ports[i], NULL);
3274 void do_usb_add(const char *devname)
3277 ret = usb_device_add(devname);
3279 term_printf("Could not add USB device '%s'\n", devname);
3282 void do_usb_del(const char *devname)
3285 ret = usb_device_del(devname);
3287 term_printf("Could not remove USB device '%s'\n", devname);
3294 const char *speed_str;
3297 term_printf("USB support not enabled\n");
3301 for(i = 0; i < MAX_VM_USB_PORTS; i++) {
3302 dev = vm_usb_ports[i]->dev;
3304 term_printf("Hub port %d:\n", i);
3305 switch(dev->speed) {
3309 case USB_SPEED_FULL:
3312 case USB_SPEED_HIGH:
3319 term_printf(" Device %d.%d, speed %s Mb/s\n",
3320 0, dev->addr, speed_str);
3325 /***********************************************************/
3328 static char *pid_filename;
3330 /* Remove PID file. Called on normal exit */
3332 static void remove_pidfile(void)
3334 unlink (pid_filename);
3337 static void create_pidfile(const char *filename)
3339 struct stat pidstat;
3342 /* Try to write our PID to the named file */
3343 if (stat(filename, &pidstat) < 0) {
3344 if (errno == ENOENT) {
3345 if ((f = fopen (filename, "w")) == NULL) {
3346 perror("Opening pidfile");
3349 fprintf(f, "%d\n", getpid());
3351 pid_filename = qemu_strdup(filename);
3352 if (!pid_filename) {
3353 fprintf(stderr, "Could not save PID filename");
3356 atexit(remove_pidfile);
3359 fprintf(stderr, "%s already exists. Remove it and try again.\n",
3365 /***********************************************************/
3368 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
3372 static void dumb_resize(DisplayState *ds, int w, int h)
3376 static void dumb_refresh(DisplayState *ds)
3381 void dumb_display_init(DisplayState *ds)
3386 ds->dpy_update = dumb_update;
3387 ds->dpy_resize = dumb_resize;
3388 ds->dpy_refresh = dumb_refresh;
3391 #if !defined(CONFIG_SOFTMMU)
3392 /***********************************************************/
3393 /* cpu signal handler */
3394 static void host_segv_handler(int host_signum, siginfo_t *info,
3397 if (cpu_signal_handler(host_signum, info, puc))
3399 if (stdio_nb_clients > 0)
3405 /***********************************************************/
3408 #define MAX_IO_HANDLERS 64
3410 typedef struct IOHandlerRecord {
3412 IOCanRWHandler *fd_read_poll;
3414 IOHandler *fd_write;
3416 /* temporary data */
3418 struct IOHandlerRecord *next;
3421 static IOHandlerRecord *first_io_handler;
3423 /* XXX: fd_read_poll should be suppressed, but an API change is
3424 necessary in the character devices to suppress fd_can_read(). */
3425 int qemu_set_fd_handler2(int fd,
3426 IOCanRWHandler *fd_read_poll,
3428 IOHandler *fd_write,
3431 IOHandlerRecord **pioh, *ioh;
3433 if (!fd_read && !fd_write) {
3434 pioh = &first_io_handler;
3439 if (ioh->fd == fd) {
3447 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3451 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
3454 ioh->next = first_io_handler;
3455 first_io_handler = ioh;
3458 ioh->fd_read_poll = fd_read_poll;
3459 ioh->fd_read = fd_read;
3460 ioh->fd_write = fd_write;
3461 ioh->opaque = opaque;
3466 int qemu_set_fd_handler(int fd,
3468 IOHandler *fd_write,
3471 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
3474 /***********************************************************/
3475 /* Polling handling */
3477 typedef struct PollingEntry {
3480 struct PollingEntry *next;
3483 static PollingEntry *first_polling_entry;
3485 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
3487 PollingEntry **ppe, *pe;
3488 pe = qemu_mallocz(sizeof(PollingEntry));
3492 pe->opaque = opaque;
3493 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
3498 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
3500 PollingEntry **ppe, *pe;
3501 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
3503 if (pe->func == func && pe->opaque == opaque) {
3511 /***********************************************************/
3512 /* savevm/loadvm support */
3514 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
3516 fwrite(buf, 1, size, f);
3519 void qemu_put_byte(QEMUFile *f, int v)
3524 void qemu_put_be16(QEMUFile *f, unsigned int v)
3526 qemu_put_byte(f, v >> 8);
3527 qemu_put_byte(f, v);
3530 void qemu_put_be32(QEMUFile *f, unsigned int v)
3532 qemu_put_byte(f, v >> 24);
3533 qemu_put_byte(f, v >> 16);
3534 qemu_put_byte(f, v >> 8);
3535 qemu_put_byte(f, v);
3538 void qemu_put_be64(QEMUFile *f, uint64_t v)
3540 qemu_put_be32(f, v >> 32);
3541 qemu_put_be32(f, v);
3544 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size)
3546 return fread(buf, 1, size, f);
3549 int qemu_get_byte(QEMUFile *f)
3559 unsigned int qemu_get_be16(QEMUFile *f)
3562 v = qemu_get_byte(f) << 8;
3563 v |= qemu_get_byte(f);
3567 unsigned int qemu_get_be32(QEMUFile *f)
3570 v = qemu_get_byte(f) << 24;
3571 v |= qemu_get_byte(f) << 16;
3572 v |= qemu_get_byte(f) << 8;
3573 v |= qemu_get_byte(f);
3577 uint64_t qemu_get_be64(QEMUFile *f)
3580 v = (uint64_t)qemu_get_be32(f) << 32;
3581 v |= qemu_get_be32(f);
3585 int64_t qemu_ftell(QEMUFile *f)
3590 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
3592 if (fseek(f, pos, whence) < 0)
3597 typedef struct SaveStateEntry {
3601 SaveStateHandler *save_state;
3602 LoadStateHandler *load_state;
3604 struct SaveStateEntry *next;
3607 static SaveStateEntry *first_se;
3609 int register_savevm(const char *idstr,
3612 SaveStateHandler *save_state,
3613 LoadStateHandler *load_state,
3616 SaveStateEntry *se, **pse;
3618 se = qemu_malloc(sizeof(SaveStateEntry));
3621 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
3622 se->instance_id = instance_id;
3623 se->version_id = version_id;
3624 se->save_state = save_state;
3625 se->load_state = load_state;
3626 se->opaque = opaque;
3629 /* add at the end of list */
3631 while (*pse != NULL)
3632 pse = &(*pse)->next;
3637 #define QEMU_VM_FILE_MAGIC 0x5145564d
3638 #define QEMU_VM_FILE_VERSION 0x00000001
3640 int qemu_savevm(const char *filename)
3644 int len, len_pos, cur_pos, saved_vm_running, ret;
3646 saved_vm_running = vm_running;
3649 f = fopen(filename, "wb");
3655 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
3656 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
3658 for(se = first_se; se != NULL; se = se->next) {
3660 len = strlen(se->idstr);
3661 qemu_put_byte(f, len);
3662 qemu_put_buffer(f, se->idstr, len);
3664 qemu_put_be32(f, se->instance_id);
3665 qemu_put_be32(f, se->version_id);
3667 /* record size: filled later */
3669 qemu_put_be32(f, 0);
3671 se->save_state(f, se->opaque);
3673 /* fill record size */
3675 len = ftell(f) - len_pos - 4;
3676 fseek(f, len_pos, SEEK_SET);
3677 qemu_put_be32(f, len);
3678 fseek(f, cur_pos, SEEK_SET);
3684 if (saved_vm_running)
3689 static SaveStateEntry *find_se(const char *idstr, int instance_id)
3693 for(se = first_se; se != NULL; se = se->next) {
3694 if (!strcmp(se->idstr, idstr) &&
3695 instance_id == se->instance_id)
3701 int qemu_loadvm(const char *filename)
3705 int len, cur_pos, ret, instance_id, record_len, version_id;
3706 int saved_vm_running;
3710 saved_vm_running = vm_running;
3713 f = fopen(filename, "rb");
3719 v = qemu_get_be32(f);
3720 if (v != QEMU_VM_FILE_MAGIC)
3722 v = qemu_get_be32(f);
3723 if (v != QEMU_VM_FILE_VERSION) {
3730 len = qemu_get_byte(f);
3733 qemu_get_buffer(f, idstr, len);
3735 instance_id = qemu_get_be32(f);
3736 version_id = qemu_get_be32(f);
3737 record_len = qemu_get_be32(f);
3739 printf("idstr=%s instance=0x%x version=%d len=%d\n",
3740 idstr, instance_id, version_id, record_len);
3743 se = find_se(idstr, instance_id);
3745 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
3746 instance_id, idstr);
3748 ret = se->load_state(f, se->opaque, version_id);
3750 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
3751 instance_id, idstr);
3754 /* always seek to exact end of record */
3755 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
3760 if (saved_vm_running)
3765 /***********************************************************/
3766 /* cpu save/restore */
3768 #if defined(TARGET_I386)
3770 static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
3772 qemu_put_be32(f, dt->selector);
3773 qemu_put_betl(f, dt->base);
3774 qemu_put_be32(f, dt->limit);
3775 qemu_put_be32(f, dt->flags);
3778 static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
3780 dt->selector = qemu_get_be32(f);
3781 dt->base = qemu_get_betl(f);
3782 dt->limit = qemu_get_be32(f);
3783 dt->flags = qemu_get_be32(f);
3786 void cpu_save(QEMUFile *f, void *opaque)
3788 CPUState *env = opaque;
3789 uint16_t fptag, fpus, fpuc, fpregs_format;
3793 for(i = 0; i < CPU_NB_REGS; i++)
3794 qemu_put_betls(f, &env->regs[i]);
3795 qemu_put_betls(f, &env->eip);
3796 qemu_put_betls(f, &env->eflags);
3797 hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
3798 qemu_put_be32s(f, &hflags);
3802 fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
3804 for(i = 0; i < 8; i++) {
3805 fptag |= ((!env->fptags[i]) << i);
3808 qemu_put_be16s(f, &fpuc);
3809 qemu_put_be16s(f, &fpus);
3810 qemu_put_be16s(f, &fptag);
3812 #ifdef USE_X86LDOUBLE
3817 qemu_put_be16s(f, &fpregs_format);
3819 for(i = 0; i < 8; i++) {
3820 #ifdef USE_X86LDOUBLE
3824 /* we save the real CPU data (in case of MMX usage only 'mant'
3825 contains the MMX register */
3826 cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
3827 qemu_put_be64(f, mant);
3828 qemu_put_be16(f, exp);
3831 /* if we use doubles for float emulation, we save the doubles to
3832 avoid losing information in case of MMX usage. It can give
3833 problems if the image is restored on a CPU where long
3834 doubles are used instead. */
3835 qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
3839 for(i = 0; i < 6; i++)
3840 cpu_put_seg(f, &env->segs[i]);
3841 cpu_put_seg(f, &env->ldt);
3842 cpu_put_seg(f, &env->tr);
3843 cpu_put_seg(f, &env->gdt);
3844 cpu_put_seg(f, &env->idt);
3846 qemu_put_be32s(f, &env->sysenter_cs);
3847 qemu_put_be32s(f, &env->sysenter_esp);
3848 qemu_put_be32s(f, &env->sysenter_eip);
3850 qemu_put_betls(f, &env->cr[0]);
3851 qemu_put_betls(f, &env->cr[2]);
3852 qemu_put_betls(f, &env->cr[3]);
3853 qemu_put_betls(f, &env->cr[4]);
3855 for(i = 0; i < 8; i++)
3856 qemu_put_betls(f, &env->dr[i]);
3859 qemu_put_be32s(f, &env->a20_mask);
3862 qemu_put_be32s(f, &env->mxcsr);
3863 for(i = 0; i < CPU_NB_REGS; i++) {
3864 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
3865 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
3868 #ifdef TARGET_X86_64
3869 qemu_put_be64s(f, &env->efer);
3870 qemu_put_be64s(f, &env->star);
3871 qemu_put_be64s(f, &env->lstar);
3872 qemu_put_be64s(f, &env->cstar);
3873 qemu_put_be64s(f, &env->fmask);
3874 qemu_put_be64s(f, &env->kernelgsbase);
3878 #ifdef USE_X86LDOUBLE
3879 /* XXX: add that in a FPU generic layer */
3880 union x86_longdouble {
3885 #define MANTD1(fp) (fp & ((1LL << 52) - 1))
3886 #define EXPBIAS1 1023
3887 #define EXPD1(fp) ((fp >> 52) & 0x7FF)
3888 #define SIGND1(fp) ((fp >> 32) & 0x80000000)
3890 static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
3894 p->mant = (MANTD1(temp) << 11) | (1LL << 63);
3895 /* exponent + sign */
3896 e = EXPD1(temp) - EXPBIAS1 + 16383;
3897 e |= SIGND1(temp) >> 16;
3902 int cpu_load(QEMUFile *f, void *opaque, int version_id)
3904 CPUState *env = opaque;
3907 uint16_t fpus, fpuc, fptag, fpregs_format;
3909 if (version_id != 3)
3911 for(i = 0; i < CPU_NB_REGS; i++)
3912 qemu_get_betls(f, &env->regs[i]);
3913 qemu_get_betls(f, &env->eip);
3914 qemu_get_betls(f, &env->eflags);
3915 qemu_get_be32s(f, &hflags);
3917 qemu_get_be16s(f, &fpuc);
3918 qemu_get_be16s(f, &fpus);
3919 qemu_get_be16s(f, &fptag);
3920 qemu_get_be16s(f, &fpregs_format);
3922 /* NOTE: we cannot always restore the FPU state if the image come
3923 from a host with a different 'USE_X86LDOUBLE' define. We guess
3924 if we are in an MMX state to restore correctly in that case. */
3925 guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
3926 for(i = 0; i < 8; i++) {
3930 switch(fpregs_format) {
3932 mant = qemu_get_be64(f);
3933 exp = qemu_get_be16(f);
3934 #ifdef USE_X86LDOUBLE
3935 env->fpregs[i].d = cpu_set_fp80(mant, exp);
3937 /* difficult case */
3939 env->fpregs[i].mmx.MMX_Q(0) = mant;
3941 env->fpregs[i].d = cpu_set_fp80(mant, exp);
3945 mant = qemu_get_be64(f);
3946 #ifdef USE_X86LDOUBLE
3948 union x86_longdouble *p;
3949 /* difficult case */
3950 p = (void *)&env->fpregs[i];
3955 fp64_to_fp80(p, mant);
3959 env->fpregs[i].mmx.MMX_Q(0) = mant;
3968 /* XXX: restore FPU round state */
3969 env->fpstt = (fpus >> 11) & 7;
3970 env->fpus = fpus & ~0x3800;
3972 for(i = 0; i < 8; i++) {
3973 env->fptags[i] = (fptag >> i) & 1;
3976 for(i = 0; i < 6; i++)
3977 cpu_get_seg(f, &env->segs[i]);
3978 cpu_get_seg(f, &env->ldt);
3979 cpu_get_seg(f, &env->tr);
3980 cpu_get_seg(f, &env->gdt);
3981 cpu_get_seg(f, &env->idt);
3983 qemu_get_be32s(f, &env->sysenter_cs);
3984 qemu_get_be32s(f, &env->sysenter_esp);
3985 qemu_get_be32s(f, &env->sysenter_eip);
3987 qemu_get_betls(f, &env->cr[0]);
3988 qemu_get_betls(f, &env->cr[2]);
3989 qemu_get_betls(f, &env->cr[3]);
3990 qemu_get_betls(f, &env->cr[4]);
3992 for(i = 0; i < 8; i++)
3993 qemu_get_betls(f, &env->dr[i]);
3996 qemu_get_be32s(f, &env->a20_mask);
3998 qemu_get_be32s(f, &env->mxcsr);
3999 for(i = 0; i < CPU_NB_REGS; i++) {
4000 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
4001 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
4004 #ifdef TARGET_X86_64
4005 qemu_get_be64s(f, &env->efer);
4006 qemu_get_be64s(f, &env->star);
4007 qemu_get_be64s(f, &env->lstar);
4008 qemu_get_be64s(f, &env->cstar);
4009 qemu_get_be64s(f, &env->fmask);
4010 qemu_get_be64s(f, &env->kernelgsbase);
4013 /* XXX: compute hflags from scratch, except for CPL and IIF */
4014 env->hflags = hflags;
4019 #elif defined(TARGET_PPC)
4020 void cpu_save(QEMUFile *f, void *opaque)
4024 int cpu_load(QEMUFile *f, void *opaque, int version_id)
4029 #elif defined(TARGET_MIPS)
4030 void cpu_save(QEMUFile *f, void *opaque)
4034 int cpu_load(QEMUFile *f, void *opaque, int version_id)
4039 #elif defined(TARGET_SPARC)
4040 void cpu_save(QEMUFile *f, void *opaque)
4042 CPUState *env = opaque;
4046 for(i = 0; i < 8; i++)
4047 qemu_put_betls(f, &env->gregs[i]);
4048 for(i = 0; i < NWINDOWS * 16; i++)
4049 qemu_put_betls(f, &env->regbase[i]);
4052 for(i = 0; i < TARGET_FPREGS; i++) {
4058 qemu_put_betl(f, u.i);
4061 qemu_put_betls(f, &env->pc);
4062 qemu_put_betls(f, &env->npc);
4063 qemu_put_betls(f, &env->y);
4065 qemu_put_be32(f, tmp);
4066 qemu_put_betls(f, &env->fsr);
4067 qemu_put_betls(f, &env->tbr);
4068 #ifndef TARGET_SPARC64
4069 qemu_put_be32s(f, &env->wim);
4071 for(i = 0; i < 16; i++)
4072 qemu_put_be32s(f, &env->mmuregs[i]);
4076 int cpu_load(QEMUFile *f, void *opaque, int version_id)
4078 CPUState *env = opaque;
4082 for(i = 0; i < 8; i++)
4083 qemu_get_betls(f, &env->gregs[i]);
4084 for(i = 0; i < NWINDOWS * 16; i++)
4085 qemu_get_betls(f, &env->regbase[i]);
4088 for(i = 0; i < TARGET_FPREGS; i++) {
4093 u.i = qemu_get_betl(f);
4097 qemu_get_betls(f, &env->pc);
4098 qemu_get_betls(f, &env->npc);
4099 qemu_get_betls(f, &env->y);
4100 tmp = qemu_get_be32(f);
4101 env->cwp = 0; /* needed to ensure that the wrapping registers are
4102 correctly updated */
4104 qemu_get_betls(f, &env->fsr);
4105 qemu_get_betls(f, &env->tbr);
4106 #ifndef TARGET_SPARC64
4107 qemu_get_be32s(f, &env->wim);
4109 for(i = 0; i < 16; i++)
4110 qemu_get_be32s(f, &env->mmuregs[i]);
4116 #elif defined(TARGET_ARM)
4118 /* ??? Need to implement these. */
4119 void cpu_save(QEMUFile *f, void *opaque)
4123 int cpu_load(QEMUFile *f, void *opaque, int version_id)
4130 #warning No CPU save/restore functions
4134 /***********************************************************/
4135 /* ram save/restore */
4137 /* we just avoid storing empty pages */
4138 static void ram_put_page(QEMUFile *f, const uint8_t *buf, int len)
4143 for(i = 1; i < len; i++) {
4147 qemu_put_byte(f, 1);
4148 qemu_put_byte(f, v);
4151 qemu_put_byte(f, 0);
4152 qemu_put_buffer(f, buf, len);
4155 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
4159 v = qemu_get_byte(f);
4162 if (qemu_get_buffer(f, buf, len) != len)
4166 v = qemu_get_byte(f);
4167 memset(buf, v, len);
4175 static void ram_save(QEMUFile *f, void *opaque)
4178 qemu_put_be32(f, phys_ram_size);
4179 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
4180 ram_put_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
4184 static int ram_load(QEMUFile *f, void *opaque, int version_id)
4188 if (version_id != 1)
4190 if (qemu_get_be32(f) != phys_ram_size)
4192 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
4193 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
4200 /***********************************************************/
4201 /* machine registration */
4203 QEMUMachine *first_machine = NULL;
4205 int qemu_register_machine(QEMUMachine *m)
4208 pm = &first_machine;
4216 QEMUMachine *find_machine(const char *name)
4220 for(m = first_machine; m != NULL; m = m->next) {
4221 if (!strcmp(m->name, name))
4227 /***********************************************************/
4228 /* main execution loop */
4230 void gui_update(void *opaque)
4232 display_state.dpy_refresh(&display_state);
4233 qemu_mod_timer(gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
4236 struct vm_change_state_entry {
4237 VMChangeStateHandler *cb;
4239 LIST_ENTRY (vm_change_state_entry) entries;
4242 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
4244 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
4247 VMChangeStateEntry *e;
4249 e = qemu_mallocz(sizeof (*e));
4255 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
4259 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
4261 LIST_REMOVE (e, entries);
4265 static void vm_state_notify(int running)
4267 VMChangeStateEntry *e;
4269 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
4270 e->cb(e->opaque, running);
4274 /* XXX: support several handlers */
4275 static VMStopHandler *vm_stop_cb;
4276 static void *vm_stop_opaque;
4278 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
4281 vm_stop_opaque = opaque;
4285 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
4299 void vm_stop(int reason)
4302 cpu_disable_ticks();
4306 vm_stop_cb(vm_stop_opaque, reason);
4313 /* reset/shutdown handler */
4315 typedef struct QEMUResetEntry {
4316 QEMUResetHandler *func;
4318 struct QEMUResetEntry *next;
4321 static QEMUResetEntry *first_reset_entry;
4322 static int reset_requested;
4323 static int shutdown_requested;
4324 static int powerdown_requested;
4326 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
4328 QEMUResetEntry **pre, *re;
4330 pre = &first_reset_entry;
4331 while (*pre != NULL)
4332 pre = &(*pre)->next;
4333 re = qemu_mallocz(sizeof(QEMUResetEntry));
4335 re->opaque = opaque;
4340 void qemu_system_reset(void)
4344 /* reset all devices */
4345 for(re = first_reset_entry; re != NULL; re = re->next) {
4346 re->func(re->opaque);
4350 void qemu_system_reset_request(void)
4352 reset_requested = 1;
4354 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
4357 void qemu_system_shutdown_request(void)
4359 shutdown_requested = 1;
4361 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
4364 void qemu_system_powerdown_request(void)
4366 powerdown_requested = 1;
4368 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
4371 void main_loop_wait(int timeout)
4373 IOHandlerRecord *ioh, *ioh_next;
4380 /* XXX: need to suppress polling by better using win32 events */
4382 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
4383 ret |= pe->func(pe->opaque);
4386 if (ret == 0 && timeout > 0) {
4390 /* poll any events */
4391 /* XXX: separate device handlers from system ones */
4395 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4397 (!ioh->fd_read_poll ||
4398 ioh->fd_read_poll(ioh->opaque) != 0)) {
4399 FD_SET(ioh->fd, &rfds);
4403 if (ioh->fd_write) {
4404 FD_SET(ioh->fd, &wfds);
4414 tv.tv_usec = timeout * 1000;
4416 ret = select(nfds + 1, &rfds, &wfds, NULL, &tv);
4418 /* XXX: better handling of removal */
4419 for(ioh = first_io_handler; ioh != NULL; ioh = ioh_next) {
4420 ioh_next = ioh->next;
4421 if (FD_ISSET(ioh->fd, &rfds)) {
4422 ioh->fd_read(ioh->opaque);
4424 if (FD_ISSET(ioh->fd, &wfds)) {
4425 ioh->fd_write(ioh->opaque);
4433 #if defined(CONFIG_SLIRP)
4434 /* XXX: merge with the previous select() */
4436 fd_set rfds, wfds, xfds;
4444 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
4447 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
4449 slirp_select_poll(&rfds, &wfds, &xfds);
4455 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
4456 qemu_get_clock(vm_clock));
4457 /* run dma transfers, if any */
4461 /* real time timers */
4462 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
4463 qemu_get_clock(rt_clock));
4466 static CPUState *cur_cpu;
4471 #ifdef CONFIG_PROFILER
4476 cur_cpu = first_cpu;
4483 env = env->next_cpu;
4486 #ifdef CONFIG_PROFILER
4487 ti = profile_getclock();
4489 ret = cpu_exec(env);
4490 #ifdef CONFIG_PROFILER
4491 qemu_time += profile_getclock() - ti;
4493 if (ret != EXCP_HALTED)
4495 /* all CPUs are halted ? */
4496 if (env == cur_cpu) {
4503 if (shutdown_requested) {
4504 ret = EXCP_INTERRUPT;
4507 if (reset_requested) {
4508 reset_requested = 0;
4509 qemu_system_reset();
4510 ret = EXCP_INTERRUPT;
4512 if (powerdown_requested) {
4513 powerdown_requested = 0;
4514 qemu_system_powerdown();
4515 ret = EXCP_INTERRUPT;
4517 if (ret == EXCP_DEBUG) {
4518 vm_stop(EXCP_DEBUG);
4520 /* if hlt instruction, we wait until the next IRQ */
4521 /* XXX: use timeout computed from timers */
4522 if (ret == EXCP_HLT)
4529 #ifdef CONFIG_PROFILER
4530 ti = profile_getclock();
4532 main_loop_wait(timeout);
4533 #ifdef CONFIG_PROFILER
4534 dev_time += profile_getclock() - ti;
4537 cpu_disable_ticks();
4543 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2005 Fabrice Bellard\n"
4544 "usage: %s [options] [disk_image]\n"
4546 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4548 "Standard options:\n"
4549 "-M machine select emulated machine (-M ? for list)\n"
4550 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
4551 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
4552 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
4553 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
4554 "-boot [a|c|d] boot on floppy (a), hard disk (c) or CD-ROM (d)\n"
4555 "-snapshot write to temporary files instead of disk image files\n"
4556 "-m megs set virtual RAM size to megs MB [default=%d]\n"
4557 "-smp n set the number of CPUs to 'n' [default=1]\n"
4558 "-nographic disable graphical output and redirect serial I/Os to console\n"
4560 "-k language use keyboard layout (for example \"fr\" for French)\n"
4563 "-audio-help print list of audio drivers and their options\n"
4564 "-soundhw c1,... enable audio support\n"
4565 " and only specified sound cards (comma separated list)\n"
4566 " use -soundhw ? to get the list of supported cards\n"
4567 " use -soundhw all to enable all of them\n"
4569 "-localtime set the real time clock to local time [default=utc]\n"
4570 "-full-screen start in full screen\n"
4572 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
4574 "-usb enable the USB driver (will be the default soon)\n"
4575 "-usbdevice name add the host or guest USB device 'name'\n"
4576 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
4577 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
4580 "Network options:\n"
4581 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
4582 " create a new Network Interface Card and connect it to VLAN 'n'\n"
4584 "-net user[,vlan=n][,hostname=host]\n"
4585 " connect the user mode network stack to VLAN 'n' and send\n"
4586 " hostname 'host' to DHCP clients\n"
4589 "-net tap[,vlan=n],ifname=name\n"
4590 " connect the host TAP network interface to VLAN 'n'\n"
4592 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file]\n"
4593 " connect the host TAP network interface to VLAN 'n' and use\n"
4594 " the network script 'file' (default=%s);\n"
4595 " use 'fd=h' to connect to an already opened TAP interface\n"
4597 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
4598 " connect the vlan 'n' to another VLAN using a socket connection\n"
4599 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
4600 " connect the vlan 'n' to multicast maddr and port\n"
4601 "-net none use it alone to have zero network devices; if no -net option\n"
4602 " is provided, the default is '-net nic -net user'\n"
4605 "-tftp prefix allow tftp access to files starting with prefix [-net user]\n"
4607 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
4609 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
4610 " redirect TCP or UDP connections from host to guest [-net user]\n"
4613 "Linux boot specific:\n"
4614 "-kernel bzImage use 'bzImage' as kernel image\n"
4615 "-append cmdline use 'cmdline' as kernel command line\n"
4616 "-initrd file use 'file' as initial ram disk\n"
4618 "Debug/Expert options:\n"
4619 "-monitor dev redirect the monitor to char device 'dev'\n"
4620 "-serial dev redirect the serial port to char device 'dev'\n"
4621 "-parallel dev redirect the parallel port to char device 'dev'\n"
4622 "-pidfile file Write PID to 'file'\n"
4623 "-S freeze CPU at startup (use 'c' to start execution)\n"
4624 "-s wait gdb connection to port %d\n"
4625 "-p port change gdb connection port\n"
4626 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
4627 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
4628 " translation (t=none or lba) (usually qemu can guess them)\n"
4629 "-L path set the directory for the BIOS and VGA BIOS\n"
4631 "-no-kqemu disable KQEMU kernel module usage\n"
4633 #ifdef USE_CODE_COPY
4634 "-no-code-copy disable code copy acceleration\n"
4637 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
4638 " (default is CL-GD5446 PCI VGA)\n"
4640 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
4642 "During emulation, the following keys are useful:\n"
4643 "ctrl-alt-f toggle full screen\n"
4644 "ctrl-alt-n switch to virtual console 'n'\n"
4645 "ctrl-alt toggle mouse and keyboard grab\n"
4647 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4649 #ifdef CONFIG_SOFTMMU
4656 DEFAULT_NETWORK_SCRIPT,
4658 DEFAULT_GDBSTUB_PORT,
4660 #ifndef CONFIG_SOFTMMU
4662 "NOTE: this version of QEMU is faster but it needs slightly patched OSes to\n"
4663 "work. Please use the 'qemu' executable to have a more accurate (but slower)\n"
4669 #define HAS_ARG 0x0001
4683 QEMU_OPTION_snapshot,
4685 QEMU_OPTION_nographic,
4687 QEMU_OPTION_audio_help,
4688 QEMU_OPTION_soundhw,
4706 QEMU_OPTION_no_code_copy,
4708 QEMU_OPTION_localtime,
4709 QEMU_OPTION_cirrusvga,
4711 QEMU_OPTION_std_vga,
4712 QEMU_OPTION_monitor,
4714 QEMU_OPTION_parallel,
4716 QEMU_OPTION_full_screen,
4717 QEMU_OPTION_pidfile,
4718 QEMU_OPTION_no_kqemu,
4719 QEMU_OPTION_kernel_kqemu,
4720 QEMU_OPTION_win2k_hack,
4722 QEMU_OPTION_usbdevice,
4726 typedef struct QEMUOption {
4732 const QEMUOption qemu_options[] = {
4733 { "h", 0, QEMU_OPTION_h },
4735 { "M", HAS_ARG, QEMU_OPTION_M },
4736 { "fda", HAS_ARG, QEMU_OPTION_fda },
4737 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
4738 { "hda", HAS_ARG, QEMU_OPTION_hda },
4739 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
4740 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
4741 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
4742 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
4743 { "boot", HAS_ARG, QEMU_OPTION_boot },
4744 { "snapshot", 0, QEMU_OPTION_snapshot },
4745 { "m", HAS_ARG, QEMU_OPTION_m },
4746 { "nographic", 0, QEMU_OPTION_nographic },
4747 { "k", HAS_ARG, QEMU_OPTION_k },
4749 { "audio-help", 0, QEMU_OPTION_audio_help },
4750 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
4753 { "net", HAS_ARG, QEMU_OPTION_net},
4755 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
4757 { "smb", HAS_ARG, QEMU_OPTION_smb },
4759 { "redir", HAS_ARG, QEMU_OPTION_redir },
4762 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
4763 { "append", HAS_ARG, QEMU_OPTION_append },
4764 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
4766 { "S", 0, QEMU_OPTION_S },
4767 { "s", 0, QEMU_OPTION_s },
4768 { "p", HAS_ARG, QEMU_OPTION_p },
4769 { "d", HAS_ARG, QEMU_OPTION_d },
4770 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
4771 { "L", HAS_ARG, QEMU_OPTION_L },
4772 { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
4774 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
4775 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
4777 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
4778 { "g", 1, QEMU_OPTION_g },
4780 { "localtime", 0, QEMU_OPTION_localtime },
4781 { "std-vga", 0, QEMU_OPTION_std_vga },
4782 { "monitor", 1, QEMU_OPTION_monitor },
4783 { "serial", 1, QEMU_OPTION_serial },
4784 { "parallel", 1, QEMU_OPTION_parallel },
4785 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
4786 { "full-screen", 0, QEMU_OPTION_full_screen },
4787 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
4788 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
4789 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
4790 { "smp", HAS_ARG, QEMU_OPTION_smp },
4792 /* temporary options */
4793 { "usb", 0, QEMU_OPTION_usb },
4794 { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
4798 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
4800 /* this stack is only used during signal handling */
4801 #define SIGNAL_STACK_SIZE 32768
4803 static uint8_t *signal_stack;
4807 /* password input */
4809 static BlockDriverState *get_bdrv(int index)
4811 BlockDriverState *bs;
4814 bs = bs_table[index];
4815 } else if (index < 6) {
4816 bs = fd_table[index - 4];
4823 static void read_passwords(void)
4825 BlockDriverState *bs;
4829 for(i = 0; i < 6; i++) {
4831 if (bs && bdrv_is_encrypted(bs)) {
4832 term_printf("%s is encrypted.\n", bdrv_get_device_name(bs));
4833 for(j = 0; j < 3; j++) {
4834 monitor_readline("Password: ",
4835 1, password, sizeof(password));
4836 if (bdrv_set_key(bs, password) == 0)
4838 term_printf("invalid password\n");
4844 /* XXX: currently we cannot use simultaneously different CPUs */
4845 void register_machines(void)
4847 #if defined(TARGET_I386)
4848 qemu_register_machine(&pc_machine);
4849 qemu_register_machine(&isapc_machine);
4850 #elif defined(TARGET_PPC)
4851 qemu_register_machine(&heathrow_machine);
4852 qemu_register_machine(&core99_machine);
4853 qemu_register_machine(&prep_machine);
4854 #elif defined(TARGET_MIPS)
4855 qemu_register_machine(&mips_machine);
4856 #elif defined(TARGET_SPARC)
4857 #ifdef TARGET_SPARC64
4858 qemu_register_machine(&sun4u_machine);
4860 qemu_register_machine(&sun4m_machine);
4862 #elif defined(TARGET_ARM)
4863 qemu_register_machine(&integratorcp926_machine);
4864 qemu_register_machine(&integratorcp1026_machine);
4865 qemu_register_machine(&versatilepb_machine);
4867 #error unsupported CPU
4872 struct soundhw soundhw[] = {
4879 { .init_isa = pcspk_audio_init }
4884 "Creative Sound Blaster 16",
4887 { .init_isa = SB16_init }
4894 "Yamaha YMF262 (OPL3)",
4896 "Yamaha YM3812 (OPL2)",
4900 { .init_isa = Adlib_init }
4907 "Gravis Ultrasound GF1",
4910 { .init_isa = GUS_init }
4916 "ENSONIQ AudioPCI ES1370",
4919 { .init_pci = es1370_init }
4922 { NULL, NULL, 0, 0, { NULL } }
4925 static void select_soundhw (const char *optarg)
4929 if (*optarg == '?') {
4932 printf ("Valid sound card names (comma separated):\n");
4933 for (c = soundhw; c->name; ++c) {
4934 printf ("%-11s %s\n", c->name, c->descr);
4936 printf ("\n-soundhw all will enable all of the above\n");
4937 exit (*optarg != '?');
4945 if (!strcmp (optarg, "all")) {
4946 for (c = soundhw; c->name; ++c) {
4954 e = strchr (p, ',');
4955 l = !e ? strlen (p) : (size_t) (e - p);
4957 for (c = soundhw; c->name; ++c) {
4958 if (!strncmp (c->name, p, l)) {
4967 "Unknown sound card name (too big to show)\n");
4970 fprintf (stderr, "Unknown sound card name `%.*s'\n",
4975 p += l + (e != NULL);
4979 goto show_valid_cards;
4984 #define MAX_NET_CLIENTS 32
4986 int main(int argc, char **argv)
4988 #ifdef CONFIG_GDBSTUB
4989 int use_gdbstub, gdbstub_port;
4992 int snapshot, linux_boot;
4993 const char *initrd_filename;
4994 const char *hd_filename[MAX_DISKS], *fd_filename[MAX_FD];
4995 const char *kernel_filename, *kernel_cmdline;
4996 DisplayState *ds = &display_state;
4997 int cyls, heads, secs, translation;
4998 int start_emulation = 1;
4999 char net_clients[MAX_NET_CLIENTS][256];
5002 const char *r, *optarg;
5003 CharDriverState *monitor_hd;
5004 char monitor_device[128];
5005 char serial_devices[MAX_SERIAL_PORTS][128];
5006 int serial_device_index;
5007 char parallel_devices[MAX_PARALLEL_PORTS][128];
5008 int parallel_device_index;
5009 const char *loadvm = NULL;
5010 QEMUMachine *machine;
5011 char usb_devices[MAX_VM_USB_PORTS][128];
5012 int usb_devices_index;
5014 LIST_INIT (&vm_change_state_head);
5015 #if !defined(CONFIG_SOFTMMU)
5016 /* we never want that malloc() uses mmap() */
5017 mallopt(M_MMAP_THRESHOLD, 4096 * 1024);
5019 register_machines();
5020 machine = first_machine;
5021 initrd_filename = NULL;
5022 for(i = 0; i < MAX_FD; i++)
5023 fd_filename[i] = NULL;
5024 for(i = 0; i < MAX_DISKS; i++)
5025 hd_filename[i] = NULL;
5026 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5027 vga_ram_size = VGA_RAM_SIZE;
5028 bios_size = BIOS_SIZE;
5029 #ifdef CONFIG_GDBSTUB
5031 gdbstub_port = DEFAULT_GDBSTUB_PORT;
5035 kernel_filename = NULL;
5036 kernel_cmdline = "";
5042 cyls = heads = secs = 0;
5043 translation = BIOS_ATA_TRANSLATION_AUTO;
5044 pstrcpy(monitor_device, sizeof(monitor_device), "vc");
5046 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
5047 for(i = 1; i < MAX_SERIAL_PORTS; i++)
5048 serial_devices[i][0] = '\0';
5049 serial_device_index = 0;
5051 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
5052 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
5053 parallel_devices[i][0] = '\0';
5054 parallel_device_index = 0;
5056 usb_devices_index = 0;
5061 /* default mac address of the first network interface */
5069 hd_filename[0] = argv[optind++];
5071 const QEMUOption *popt;
5074 popt = qemu_options;
5077 fprintf(stderr, "%s: invalid option -- '%s'\n",
5081 if (!strcmp(popt->name, r + 1))
5085 if (popt->flags & HAS_ARG) {
5086 if (optind >= argc) {
5087 fprintf(stderr, "%s: option '%s' requires an argument\n",
5091 optarg = argv[optind++];
5096 switch(popt->index) {
5098 machine = find_machine(optarg);
5101 printf("Supported machines are:\n");
5102 for(m = first_machine; m != NULL; m = m->next) {
5103 printf("%-10s %s%s\n",
5105 m == first_machine ? " (default)" : "");
5110 case QEMU_OPTION_initrd:
5111 initrd_filename = optarg;
5113 case QEMU_OPTION_hda:
5114 case QEMU_OPTION_hdb:
5115 case QEMU_OPTION_hdc:
5116 case QEMU_OPTION_hdd:
5119 hd_index = popt->index - QEMU_OPTION_hda;
5120 hd_filename[hd_index] = optarg;
5121 if (hd_index == cdrom_index)
5125 case QEMU_OPTION_snapshot:
5128 case QEMU_OPTION_hdachs:
5132 cyls = strtol(p, (char **)&p, 0);
5133 if (cyls < 1 || cyls > 16383)
5138 heads = strtol(p, (char **)&p, 0);
5139 if (heads < 1 || heads > 16)
5144 secs = strtol(p, (char **)&p, 0);
5145 if (secs < 1 || secs > 63)
5149 if (!strcmp(p, "none"))
5150 translation = BIOS_ATA_TRANSLATION_NONE;
5151 else if (!strcmp(p, "lba"))
5152 translation = BIOS_ATA_TRANSLATION_LBA;
5153 else if (!strcmp(p, "auto"))
5154 translation = BIOS_ATA_TRANSLATION_AUTO;
5157 } else if (*p != '\0') {
5159 fprintf(stderr, "qemu: invalid physical CHS format\n");
5164 case QEMU_OPTION_nographic:
5165 pstrcpy(monitor_device, sizeof(monitor_device), "stdio");
5166 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "stdio");
5169 case QEMU_OPTION_kernel:
5170 kernel_filename = optarg;
5172 case QEMU_OPTION_append:
5173 kernel_cmdline = optarg;
5175 case QEMU_OPTION_cdrom:
5176 if (cdrom_index >= 0) {
5177 hd_filename[cdrom_index] = optarg;
5180 case QEMU_OPTION_boot:
5181 boot_device = optarg[0];
5182 if (boot_device != 'a' &&
5185 boot_device != 'n' &&
5187 boot_device != 'c' && boot_device != 'd') {
5188 fprintf(stderr, "qemu: invalid boot device '%c'\n", boot_device);
5192 case QEMU_OPTION_fda:
5193 fd_filename[0] = optarg;
5195 case QEMU_OPTION_fdb:
5196 fd_filename[1] = optarg;
5198 case QEMU_OPTION_no_code_copy:
5199 code_copy_enabled = 0;
5201 case QEMU_OPTION_net:
5202 if (nb_net_clients >= MAX_NET_CLIENTS) {
5203 fprintf(stderr, "qemu: too many network clients\n");
5206 pstrcpy(net_clients[nb_net_clients],
5207 sizeof(net_clients[0]),
5212 case QEMU_OPTION_tftp:
5213 tftp_prefix = optarg;
5216 case QEMU_OPTION_smb:
5217 net_slirp_smb(optarg);
5220 case QEMU_OPTION_redir:
5221 net_slirp_redir(optarg);
5225 case QEMU_OPTION_audio_help:
5229 case QEMU_OPTION_soundhw:
5230 select_soundhw (optarg);
5237 ram_size = atoi(optarg) * 1024 * 1024;
5240 if (ram_size > PHYS_RAM_MAX_SIZE) {
5241 fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
5242 PHYS_RAM_MAX_SIZE / (1024 * 1024));
5251 mask = cpu_str_to_log_mask(optarg);
5253 printf("Log items (comma separated):\n");
5254 for(item = cpu_log_items; item->mask != 0; item++) {
5255 printf("%-10s %s\n", item->name, item->help);
5262 #ifdef CONFIG_GDBSTUB
5267 gdbstub_port = atoi(optarg);
5274 start_emulation = 0;
5277 keyboard_layout = optarg;
5279 case QEMU_OPTION_localtime:
5282 case QEMU_OPTION_cirrusvga:
5283 cirrus_vga_enabled = 1;
5285 case QEMU_OPTION_std_vga:
5286 cirrus_vga_enabled = 0;
5293 w = strtol(p, (char **)&p, 10);
5296 fprintf(stderr, "qemu: invalid resolution or depth\n");
5302 h = strtol(p, (char **)&p, 10);
5307 depth = strtol(p, (char **)&p, 10);
5308 if (depth != 8 && depth != 15 && depth != 16 &&
5309 depth != 24 && depth != 32)
5311 } else if (*p == '\0') {
5312 depth = graphic_depth;
5319 graphic_depth = depth;
5322 case QEMU_OPTION_monitor:
5323 pstrcpy(monitor_device, sizeof(monitor_device), optarg);
5325 case QEMU_OPTION_serial:
5326 if (serial_device_index >= MAX_SERIAL_PORTS) {
5327 fprintf(stderr, "qemu: too many serial ports\n");
5330 pstrcpy(serial_devices[serial_device_index],
5331 sizeof(serial_devices[0]), optarg);
5332 serial_device_index++;
5334 case QEMU_OPTION_parallel:
5335 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
5336 fprintf(stderr, "qemu: too many parallel ports\n");
5339 pstrcpy(parallel_devices[parallel_device_index],
5340 sizeof(parallel_devices[0]), optarg);
5341 parallel_device_index++;
5343 case QEMU_OPTION_loadvm:
5346 case QEMU_OPTION_full_screen:
5349 case QEMU_OPTION_pidfile:
5350 create_pidfile(optarg);
5353 case QEMU_OPTION_win2k_hack:
5354 win2k_install_hack = 1;
5358 case QEMU_OPTION_no_kqemu:
5361 case QEMU_OPTION_kernel_kqemu:
5365 case QEMU_OPTION_usb:
5368 case QEMU_OPTION_usbdevice:
5370 if (usb_devices_index >= MAX_VM_USB_PORTS) {
5371 fprintf(stderr, "Too many USB devices\n");
5374 pstrcpy(usb_devices[usb_devices_index],
5375 sizeof(usb_devices[usb_devices_index]),
5377 usb_devices_index++;
5379 case QEMU_OPTION_smp:
5380 smp_cpus = atoi(optarg);
5381 if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
5382 fprintf(stderr, "Invalid number of CPUs\n");
5394 linux_boot = (kernel_filename != NULL);
5397 hd_filename[0] == '\0' &&
5398 (cdrom_index >= 0 && hd_filename[cdrom_index] == '\0') &&
5399 fd_filename[0] == '\0')
5402 /* boot to cd by default if no hard disk */
5403 if (hd_filename[0] == '\0' && boot_device == 'c') {
5404 if (fd_filename[0] != '\0')
5410 #if !defined(CONFIG_SOFTMMU)
5411 /* must avoid mmap() usage of glibc by setting a buffer "by hand" */
5413 static uint8_t stdout_buf[4096];
5414 setvbuf(stdout, stdout_buf, _IOLBF, sizeof(stdout_buf));
5417 setvbuf(stdout, NULL, _IOLBF, 0);
5424 /* init network clients */
5425 if (nb_net_clients == 0) {
5426 /* if no clients, we use a default config */
5427 pstrcpy(net_clients[0], sizeof(net_clients[0]),
5429 pstrcpy(net_clients[1], sizeof(net_clients[0]),
5434 for(i = 0;i < nb_net_clients; i++) {
5435 if (net_client_init(net_clients[i]) < 0)
5439 /* init the memory */
5440 phys_ram_size = ram_size + vga_ram_size + bios_size;
5442 #ifdef CONFIG_SOFTMMU
5443 phys_ram_base = qemu_vmalloc(phys_ram_size);
5444 if (!phys_ram_base) {
5445 fprintf(stderr, "Could not allocate physical memory\n");
5449 /* as we must map the same page at several addresses, we must use
5454 tmpdir = getenv("QEMU_TMPDIR");
5457 snprintf(phys_ram_file, sizeof(phys_ram_file), "%s/vlXXXXXX", tmpdir);
5458 if (mkstemp(phys_ram_file) < 0) {
5459 fprintf(stderr, "Could not create temporary memory file '%s'\n",
5463 phys_ram_fd = open(phys_ram_file, O_CREAT | O_TRUNC | O_RDWR, 0600);
5464 if (phys_ram_fd < 0) {
5465 fprintf(stderr, "Could not open temporary memory file '%s'\n",
5469 ftruncate(phys_ram_fd, phys_ram_size);
5470 unlink(phys_ram_file);
5471 phys_ram_base = mmap(get_mmap_addr(phys_ram_size),
5473 PROT_WRITE | PROT_READ, MAP_SHARED | MAP_FIXED,
5475 if (phys_ram_base == MAP_FAILED) {
5476 fprintf(stderr, "Could not map physical memory\n");
5482 /* we always create the cdrom drive, even if no disk is there */
5484 if (cdrom_index >= 0) {
5485 bs_table[cdrom_index] = bdrv_new("cdrom");
5486 bdrv_set_type_hint(bs_table[cdrom_index], BDRV_TYPE_CDROM);
5489 /* open the virtual block devices */
5490 for(i = 0; i < MAX_DISKS; i++) {
5491 if (hd_filename[i]) {
5494 snprintf(buf, sizeof(buf), "hd%c", i + 'a');
5495 bs_table[i] = bdrv_new(buf);
5497 if (bdrv_open(bs_table[i], hd_filename[i], snapshot) < 0) {
5498 fprintf(stderr, "qemu: could not open hard disk image '%s'\n",
5502 if (i == 0 && cyls != 0) {
5503 bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
5504 bdrv_set_translation_hint(bs_table[i], translation);
5509 /* we always create at least one floppy disk */
5510 fd_table[0] = bdrv_new("fda");
5511 bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
5513 for(i = 0; i < MAX_FD; i++) {
5514 if (fd_filename[i]) {
5517 snprintf(buf, sizeof(buf), "fd%c", i + 'a');
5518 fd_table[i] = bdrv_new(buf);
5519 bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
5521 if (fd_filename[i] != '\0') {
5522 if (bdrv_open(fd_table[i], fd_filename[i], snapshot) < 0) {
5523 fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
5531 /* init USB devices */
5533 vm_usb_hub = usb_hub_init(vm_usb_ports, MAX_VM_USB_PORTS);
5534 for(i = 0; i < usb_devices_index; i++) {
5535 if (usb_device_add(usb_devices[i]) < 0) {
5536 fprintf(stderr, "Warning: could not add USB device %s\n",
5542 register_savevm("timer", 0, 1, timer_save, timer_load, NULL);
5543 register_savevm("ram", 0, 1, ram_save, ram_load, NULL);
5546 cpu_calibrate_ticks();
5550 dumb_display_init(ds);
5552 #if defined(CONFIG_SDL)
5553 sdl_display_init(ds, full_screen);
5554 #elif defined(CONFIG_COCOA)
5555 cocoa_display_init(ds, full_screen);
5557 dumb_display_init(ds);
5561 monitor_hd = qemu_chr_open(monitor_device);
5563 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
5566 monitor_init(monitor_hd, !nographic);
5568 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5569 if (serial_devices[i][0] != '\0') {
5570 serial_hds[i] = qemu_chr_open(serial_devices[i]);
5571 if (!serial_hds[i]) {
5572 fprintf(stderr, "qemu: could not open serial device '%s'\n",
5576 if (!strcmp(serial_devices[i], "vc"))
5577 qemu_chr_printf(serial_hds[i], "serial%d console\n", i);
5581 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5582 if (parallel_devices[i][0] != '\0') {
5583 parallel_hds[i] = qemu_chr_open(parallel_devices[i]);
5584 if (!parallel_hds[i]) {
5585 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
5586 parallel_devices[i]);
5589 if (!strcmp(parallel_devices[i], "vc"))
5590 qemu_chr_printf(parallel_hds[i], "parallel%d console\n", i);
5594 /* setup cpu signal handlers for MMU / self modifying code handling */
5595 #if !defined(CONFIG_SOFTMMU)
5597 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
5600 signal_stack = memalign(16, SIGNAL_STACK_SIZE);
5601 stk.ss_sp = signal_stack;
5602 stk.ss_size = SIGNAL_STACK_SIZE;
5605 if (sigaltstack(&stk, NULL) < 0) {
5606 perror("sigaltstack");
5612 struct sigaction act;
5614 sigfillset(&act.sa_mask);
5615 act.sa_flags = SA_SIGINFO;
5616 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
5617 act.sa_flags |= SA_ONSTACK;
5619 act.sa_sigaction = host_segv_handler;
5620 sigaction(SIGSEGV, &act, NULL);
5621 sigaction(SIGBUS, &act, NULL);
5622 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
5623 sigaction(SIGFPE, &act, NULL);
5630 struct sigaction act;
5631 sigfillset(&act.sa_mask);
5633 act.sa_handler = SIG_IGN;
5634 sigaction(SIGPIPE, &act, NULL);
5639 machine->init(ram_size, vga_ram_size, boot_device,
5640 ds, fd_filename, snapshot,
5641 kernel_filename, kernel_cmdline, initrd_filename);
5643 gui_timer = qemu_new_timer(rt_clock, gui_update, NULL);
5644 qemu_mod_timer(gui_timer, qemu_get_clock(rt_clock));
5646 #ifdef CONFIG_GDBSTUB
5648 if (gdbserver_start(gdbstub_port) < 0) {
5649 fprintf(stderr, "Could not open gdbserver socket on port %d\n",
5653 printf("Waiting gdb connection on port %d\n", gdbstub_port);
5658 qemu_loadvm(loadvm);
5661 /* XXX: simplify init */
5663 if (start_emulation) {