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>
69 #define getopt_long_only getopt_long
70 #define memalign(align, size) malloc(size)
73 #include "qemu_socket.h"
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 #define PHYS_RAM_MAX_SIZE (2047 * 1024 * 1024)
98 #define DEFAULT_RAM_SIZE 144
100 #define DEFAULT_RAM_SIZE 128
103 #define GUI_REFRESH_INTERVAL 30
105 /* Max number of USB devices that can be specified on the commandline. */
106 #define MAX_USB_CMDLINE 8
108 /* XXX: use a two level table to limit memory usage */
109 #define MAX_IOPORTS 65536
111 const char *bios_dir = CONFIG_QEMU_SHAREDIR;
112 char phys_ram_file[1024];
113 void *ioport_opaque[MAX_IOPORTS];
114 IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
115 IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
116 BlockDriverState *bs_table[MAX_DISKS], *fd_table[MAX_FD];
119 static DisplayState display_state;
121 const char* keyboard_layout = NULL;
122 int64_t ticks_per_sec;
123 int boot_device = 'c';
125 int pit_min_timer_count = 0;
127 NICInfo nd_table[MAX_NICS];
128 QEMUTimer *gui_timer;
131 int cirrus_vga_enabled = 1;
133 int graphic_width = 1024;
134 int graphic_height = 768;
136 int graphic_width = 800;
137 int graphic_height = 600;
139 int graphic_depth = 15;
141 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
142 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
144 int win2k_install_hack = 0;
147 static VLANState *first_vlan;
149 int vnc_display = -1;
150 #if defined(TARGET_SPARC)
152 #elif defined(TARGET_I386)
157 int acpi_enabled = 1;
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)
522 QueryPerformanceCounter(&ti);
526 asm volatile ("rdtsc" : "=A" (val));
531 #elif defined(__x86_64__)
533 int64_t cpu_get_real_ticks(void)
537 asm volatile("rdtsc" : "=a" (low), "=d" (high));
544 #elif defined(__ia64)
546 int64_t cpu_get_real_ticks(void)
549 asm volatile ("mov %0 = ar.itc" : "=r"(val) :: "memory");
553 #elif defined(__s390__)
555 int64_t cpu_get_real_ticks(void)
558 asm volatile("stck 0(%1)" : "=m" (val) : "a" (&val) : "cc");
562 #elif defined(__sparc__) && defined(HOST_SOLARIS)
564 uint64_t cpu_get_real_ticks (void)
568 asm volatile("rd %%tick,%0" : "=r"(rval));
578 asm volatile("rd %%tick,%1; srlx %1,32,%0"
579 : "=r"(rval.i32.high), "=r"(rval.i32.low));
585 #error unsupported CPU
588 static int64_t cpu_ticks_prev;
589 static int64_t cpu_ticks_offset;
590 static int cpu_ticks_enabled;
592 static inline int64_t cpu_get_ticks(void)
594 if (!cpu_ticks_enabled) {
595 return cpu_ticks_offset;
598 ticks = cpu_get_real_ticks();
599 if (cpu_ticks_prev > ticks) {
600 /* Note: non increasing ticks may happen if the host uses
602 cpu_ticks_offset += cpu_ticks_prev - ticks;
604 cpu_ticks_prev = ticks;
605 return ticks + cpu_ticks_offset;
609 /* enable cpu_get_ticks() */
610 void cpu_enable_ticks(void)
612 if (!cpu_ticks_enabled) {
613 cpu_ticks_offset -= cpu_get_real_ticks();
614 cpu_ticks_enabled = 1;
618 /* disable cpu_get_ticks() : the clock is stopped. You must not call
619 cpu_get_ticks() after that. */
620 void cpu_disable_ticks(void)
622 if (cpu_ticks_enabled) {
623 cpu_ticks_offset = cpu_get_ticks();
624 cpu_ticks_enabled = 0;
629 void cpu_calibrate_ticks(void)
634 ret = QueryPerformanceFrequency(&freq);
636 fprintf(stderr, "Could not calibrate ticks\n");
639 ticks_per_sec = freq.QuadPart;
643 static int64_t get_clock(void)
646 gettimeofday(&tv, NULL);
647 return tv.tv_sec * 1000000LL + tv.tv_usec;
650 void cpu_calibrate_ticks(void)
655 ticks = cpu_get_real_ticks();
657 usec = get_clock() - usec;
658 ticks = cpu_get_real_ticks() - ticks;
659 ticks_per_sec = (ticks * 1000000LL + (usec >> 1)) / usec;
663 /* compute with 96 bit intermediate result: (a*b)/c */
664 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
669 #ifdef WORDS_BIGENDIAN
679 rl = (uint64_t)u.l.low * (uint64_t)b;
680 rh = (uint64_t)u.l.high * (uint64_t)b;
683 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
687 #define QEMU_TIMER_REALTIME 0
688 #define QEMU_TIMER_VIRTUAL 1
692 /* XXX: add frequency */
700 struct QEMUTimer *next;
706 static QEMUTimer *active_timers[2];
708 static MMRESULT timerID;
709 static HANDLE host_alarm = NULL;
710 static unsigned int period = 1;
712 /* frequency of the times() clock tick */
713 static int timer_freq;
716 QEMUClock *qemu_new_clock(int type)
719 clock = qemu_mallocz(sizeof(QEMUClock));
726 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
730 ts = qemu_mallocz(sizeof(QEMUTimer));
737 void qemu_free_timer(QEMUTimer *ts)
742 /* stop a timer, but do not dealloc it */
743 void qemu_del_timer(QEMUTimer *ts)
747 /* NOTE: this code must be signal safe because
748 qemu_timer_expired() can be called from a signal. */
749 pt = &active_timers[ts->clock->type];
762 /* modify the current timer so that it will be fired when current_time
763 >= expire_time. The corresponding callback will be called. */
764 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
770 /* add the timer in the sorted list */
771 /* NOTE: this code must be signal safe because
772 qemu_timer_expired() can be called from a signal. */
773 pt = &active_timers[ts->clock->type];
778 if (t->expire_time > expire_time)
782 ts->expire_time = expire_time;
787 int qemu_timer_pending(QEMUTimer *ts)
790 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
797 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
801 return (timer_head->expire_time <= current_time);
804 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
810 if (!ts || ts->expire_time > current_time)
812 /* remove timer from the list before calling the callback */
813 *ptimer_head = ts->next;
816 /* run the callback (the timer list can be modified) */
821 int64_t qemu_get_clock(QEMUClock *clock)
823 switch(clock->type) {
824 case QEMU_TIMER_REALTIME:
826 return GetTickCount();
831 /* Note that using gettimeofday() is not a good solution
832 for timers because its value change when the date is
834 if (timer_freq == 100) {
835 return times(&tp) * 10;
837 return ((int64_t)times(&tp) * 1000) / timer_freq;
842 case QEMU_TIMER_VIRTUAL:
843 return cpu_get_ticks();
848 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
850 uint64_t expire_time;
852 if (qemu_timer_pending(ts)) {
853 expire_time = ts->expire_time;
857 qemu_put_be64(f, expire_time);
860 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
862 uint64_t expire_time;
864 expire_time = qemu_get_be64(f);
865 if (expire_time != -1) {
866 qemu_mod_timer(ts, expire_time);
872 static void timer_save(QEMUFile *f, void *opaque)
874 if (cpu_ticks_enabled) {
875 hw_error("cannot save state if virtual timers are running");
877 qemu_put_be64s(f, &cpu_ticks_offset);
878 qemu_put_be64s(f, &ticks_per_sec);
881 static int timer_load(QEMUFile *f, void *opaque, int version_id)
885 if (cpu_ticks_enabled) {
888 qemu_get_be64s(f, &cpu_ticks_offset);
889 qemu_get_be64s(f, &ticks_per_sec);
894 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
895 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
897 static void host_alarm_handler(int host_signum)
901 #define DISP_FREQ 1000
903 static int64_t delta_min = INT64_MAX;
904 static int64_t delta_max, delta_cum, last_clock, delta, ti;
906 ti = qemu_get_clock(vm_clock);
907 if (last_clock != 0) {
908 delta = ti - last_clock;
909 if (delta < delta_min)
911 if (delta > delta_max)
914 if (++count == DISP_FREQ) {
915 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
916 muldiv64(delta_min, 1000000, ticks_per_sec),
917 muldiv64(delta_max, 1000000, ticks_per_sec),
918 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
919 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
921 delta_min = INT64_MAX;
929 if (qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
930 qemu_get_clock(vm_clock)) ||
931 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
932 qemu_get_clock(rt_clock))) {
934 SetEvent(host_alarm);
936 CPUState *env = cpu_single_env;
938 /* stop the currently executing cpu because a timer occured */
939 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
941 if (env->kqemu_enabled) {
942 kqemu_cpu_interrupt(env);
951 #if defined(__linux__)
953 #define RTC_FREQ 1024
957 static int start_rtc_timer(void)
959 rtc_fd = open("/dev/rtc", O_RDONLY);
962 if (ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
963 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
964 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
965 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
968 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
973 pit_min_timer_count = PIT_FREQ / RTC_FREQ;
979 static int start_rtc_timer(void)
984 #endif /* !defined(__linux__) */
986 #endif /* !defined(_WIN32) */
988 static void init_timers(void)
990 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
991 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
998 ZeroMemory(&tc, sizeof(TIMECAPS));
999 timeGetDevCaps(&tc, sizeof(TIMECAPS));
1000 if (period < tc.wPeriodMin)
1001 period = tc.wPeriodMin;
1002 timeBeginPeriod(period);
1003 timerID = timeSetEvent(1, // interval (ms)
1004 period, // resolution
1005 host_alarm_handler, // function
1006 (DWORD)&count, // user parameter
1007 TIME_PERIODIC | TIME_CALLBACK_FUNCTION);
1009 perror("failed timer alarm");
1012 host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1014 perror("failed CreateEvent");
1017 qemu_add_wait_object(host_alarm, NULL, NULL);
1019 pit_min_timer_count = ((uint64_t)10000 * PIT_FREQ) / 1000000;
1022 struct sigaction act;
1023 struct itimerval itv;
1025 /* get times() syscall frequency */
1026 timer_freq = sysconf(_SC_CLK_TCK);
1029 sigfillset(&act.sa_mask);
1031 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
1032 act.sa_flags |= SA_ONSTACK;
1034 act.sa_handler = host_alarm_handler;
1035 sigaction(SIGALRM, &act, NULL);
1037 itv.it_interval.tv_sec = 0;
1038 itv.it_interval.tv_usec = 999; /* for i386 kernel 2.6 to get 1 ms */
1039 itv.it_value.tv_sec = 0;
1040 itv.it_value.tv_usec = 10 * 1000;
1041 setitimer(ITIMER_REAL, &itv, NULL);
1042 /* we probe the tick duration of the kernel to inform the user if
1043 the emulated kernel requested a too high timer frequency */
1044 getitimer(ITIMER_REAL, &itv);
1046 #if defined(__linux__)
1047 /* XXX: force /dev/rtc usage because even 2.6 kernels may not
1048 have timers with 1 ms resolution. The correct solution will
1049 be to use the POSIX real time timers available in recent
1051 if (itv.it_interval.tv_usec > 1000 || 1) {
1052 /* try to use /dev/rtc to have a faster timer */
1053 if (start_rtc_timer() < 0)
1055 /* disable itimer */
1056 itv.it_interval.tv_sec = 0;
1057 itv.it_interval.tv_usec = 0;
1058 itv.it_value.tv_sec = 0;
1059 itv.it_value.tv_usec = 0;
1060 setitimer(ITIMER_REAL, &itv, NULL);
1063 sigaction(SIGIO, &act, NULL);
1064 fcntl(rtc_fd, F_SETFL, O_ASYNC);
1065 fcntl(rtc_fd, F_SETOWN, getpid());
1067 #endif /* defined(__linux__) */
1070 pit_min_timer_count = ((uint64_t)itv.it_interval.tv_usec *
1071 PIT_FREQ) / 1000000;
1077 void quit_timers(void)
1080 timeKillEvent(timerID);
1081 timeEndPeriod(period);
1083 CloseHandle(host_alarm);
1089 /***********************************************************/
1090 /* character device */
1092 int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1094 return s->chr_write(s, buf, len);
1097 int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1101 return s->chr_ioctl(s, cmd, arg);
1104 void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1109 vsnprintf(buf, sizeof(buf), fmt, ap);
1110 qemu_chr_write(s, buf, strlen(buf));
1114 void qemu_chr_send_event(CharDriverState *s, int event)
1116 if (s->chr_send_event)
1117 s->chr_send_event(s, event);
1120 void qemu_chr_add_read_handler(CharDriverState *s,
1121 IOCanRWHandler *fd_can_read,
1122 IOReadHandler *fd_read, void *opaque)
1124 s->chr_add_read_handler(s, fd_can_read, fd_read, opaque);
1127 void qemu_chr_add_event_handler(CharDriverState *s, IOEventHandler *chr_event)
1129 s->chr_event = chr_event;
1132 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1137 static void null_chr_add_read_handler(CharDriverState *chr,
1138 IOCanRWHandler *fd_can_read,
1139 IOReadHandler *fd_read, void *opaque)
1143 CharDriverState *qemu_chr_open_null(void)
1145 CharDriverState *chr;
1147 chr = qemu_mallocz(sizeof(CharDriverState));
1150 chr->chr_write = null_chr_write;
1151 chr->chr_add_read_handler = null_chr_add_read_handler;
1157 static void socket_cleanup(void)
1162 static int socket_init(void)
1167 ret = WSAStartup(MAKEWORD(2,2), &Data);
1169 err = WSAGetLastError();
1170 fprintf(stderr, "WSAStartup: %d\n", err);
1173 atexit(socket_cleanup);
1177 static int send_all(int fd, const uint8_t *buf, int len1)
1183 ret = send(fd, buf, len, 0);
1186 errno = WSAGetLastError();
1187 if (errno != WSAEWOULDBLOCK) {
1190 } else if (ret == 0) {
1200 void socket_set_nonblock(int fd)
1202 unsigned long opt = 1;
1203 ioctlsocket(fd, FIONBIO, &opt);
1208 static int unix_write(int fd, const uint8_t *buf, int len1)
1214 ret = write(fd, buf, len);
1216 if (errno != EINTR && errno != EAGAIN)
1218 } else if (ret == 0) {
1228 static inline int send_all(int fd, const uint8_t *buf, int len1)
1230 return unix_write(fd, buf, len1);
1233 void socket_set_nonblock(int fd)
1235 fcntl(fd, F_SETFL, O_NONBLOCK);
1237 #endif /* !_WIN32 */
1243 IOCanRWHandler *fd_can_read;
1244 IOReadHandler *fd_read;
1249 #define STDIO_MAX_CLIENTS 2
1251 static int stdio_nb_clients;
1252 static CharDriverState *stdio_clients[STDIO_MAX_CLIENTS];
1254 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1256 FDCharDriver *s = chr->opaque;
1257 return unix_write(s->fd_out, buf, len);
1260 static int fd_chr_read_poll(void *opaque)
1262 CharDriverState *chr = opaque;
1263 FDCharDriver *s = chr->opaque;
1265 s->max_size = s->fd_can_read(s->fd_opaque);
1269 static void fd_chr_read(void *opaque)
1271 CharDriverState *chr = opaque;
1272 FDCharDriver *s = chr->opaque;
1277 if (len > s->max_size)
1281 size = read(s->fd_in, buf, len);
1283 s->fd_read(s->fd_opaque, buf, size);
1287 static void fd_chr_add_read_handler(CharDriverState *chr,
1288 IOCanRWHandler *fd_can_read,
1289 IOReadHandler *fd_read, void *opaque)
1291 FDCharDriver *s = chr->opaque;
1293 if (s->fd_in >= 0) {
1294 s->fd_can_read = fd_can_read;
1295 s->fd_read = fd_read;
1296 s->fd_opaque = opaque;
1297 if (nographic && s->fd_in == 0) {
1299 qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
1300 fd_chr_read, NULL, chr);
1305 /* open a character device to a unix fd */
1306 CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
1308 CharDriverState *chr;
1311 chr = qemu_mallocz(sizeof(CharDriverState));
1314 s = qemu_mallocz(sizeof(FDCharDriver));
1322 chr->chr_write = fd_chr_write;
1323 chr->chr_add_read_handler = fd_chr_add_read_handler;
1327 CharDriverState *qemu_chr_open_file_out(const char *file_out)
1331 fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666);
1334 return qemu_chr_open_fd(-1, fd_out);
1337 CharDriverState *qemu_chr_open_pipe(const char *filename)
1341 fd = open(filename, O_RDWR | O_BINARY);
1344 return qemu_chr_open_fd(fd, fd);
1348 /* for STDIO, we handle the case where several clients use it
1351 #define TERM_ESCAPE 0x01 /* ctrl-a is used for escape */
1353 #define TERM_FIFO_MAX_SIZE 1
1355 static int term_got_escape, client_index;
1356 static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
1359 void term_print_help(void)
1362 "C-a h print this help\n"
1363 "C-a x exit emulator\n"
1364 "C-a s save disk data back to file (if -snapshot)\n"
1365 "C-a b send break (magic sysrq)\n"
1366 "C-a c switch between console and monitor\n"
1367 "C-a C-a send C-a\n"
1371 /* called when a char is received */
1372 static void stdio_received_byte(int ch)
1374 if (term_got_escape) {
1375 term_got_escape = 0;
1386 for (i = 0; i < MAX_DISKS; i++) {
1388 bdrv_commit(bs_table[i]);
1393 if (client_index < stdio_nb_clients) {
1394 CharDriverState *chr;
1397 chr = stdio_clients[client_index];
1399 chr->chr_event(s->fd_opaque, CHR_EVENT_BREAK);
1404 if (client_index >= stdio_nb_clients)
1406 if (client_index == 0) {
1407 /* send a new line in the monitor to get the prompt */
1415 } else if (ch == TERM_ESCAPE) {
1416 term_got_escape = 1;
1419 if (client_index < stdio_nb_clients) {
1421 CharDriverState *chr;
1424 chr = stdio_clients[client_index];
1426 if (s->fd_can_read(s->fd_opaque) > 0) {
1428 s->fd_read(s->fd_opaque, buf, 1);
1429 } else if (term_fifo_size == 0) {
1430 term_fifo[term_fifo_size++] = ch;
1436 static int stdio_read_poll(void *opaque)
1438 CharDriverState *chr;
1441 if (client_index < stdio_nb_clients) {
1442 chr = stdio_clients[client_index];
1444 /* try to flush the queue if needed */
1445 if (term_fifo_size != 0 && s->fd_can_read(s->fd_opaque) > 0) {
1446 s->fd_read(s->fd_opaque, term_fifo, 1);
1449 /* see if we can absorb more chars */
1450 if (term_fifo_size == 0)
1459 static void stdio_read(void *opaque)
1464 size = read(0, buf, 1);
1466 stdio_received_byte(buf[0]);
1469 /* init terminal so that we can grab keys */
1470 static struct termios oldtty;
1471 static int old_fd0_flags;
1473 static void term_exit(void)
1475 tcsetattr (0, TCSANOW, &oldtty);
1476 fcntl(0, F_SETFL, old_fd0_flags);
1479 static void term_init(void)
1483 tcgetattr (0, &tty);
1485 old_fd0_flags = fcntl(0, F_GETFL);
1487 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1488 |INLCR|IGNCR|ICRNL|IXON);
1489 tty.c_oflag |= OPOST;
1490 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1491 /* if graphical mode, we allow Ctrl-C handling */
1493 tty.c_lflag &= ~ISIG;
1494 tty.c_cflag &= ~(CSIZE|PARENB);
1497 tty.c_cc[VTIME] = 0;
1499 tcsetattr (0, TCSANOW, &tty);
1503 fcntl(0, F_SETFL, O_NONBLOCK);
1506 CharDriverState *qemu_chr_open_stdio(void)
1508 CharDriverState *chr;
1511 if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
1513 chr = qemu_chr_open_fd(0, 1);
1514 if (stdio_nb_clients == 0)
1515 qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, NULL);
1516 client_index = stdio_nb_clients;
1518 if (stdio_nb_clients != 0)
1520 chr = qemu_chr_open_fd(0, 1);
1522 stdio_clients[stdio_nb_clients++] = chr;
1523 if (stdio_nb_clients == 1) {
1524 /* set the terminal in raw mode */
1530 #if defined(__linux__)
1531 CharDriverState *qemu_chr_open_pty(void)
1534 char slave_name[1024];
1535 int master_fd, slave_fd;
1537 /* Not satisfying */
1538 if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
1542 /* Disabling local echo and line-buffered output */
1543 tcgetattr (master_fd, &tty);
1544 tty.c_lflag &= ~(ECHO|ICANON|ISIG);
1546 tty.c_cc[VTIME] = 0;
1547 tcsetattr (master_fd, TCSAFLUSH, &tty);
1549 fprintf(stderr, "char device redirected to %s\n", slave_name);
1550 return qemu_chr_open_fd(master_fd, master_fd);
1553 static void tty_serial_init(int fd, int speed,
1554 int parity, int data_bits, int stop_bits)
1560 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1561 speed, parity, data_bits, stop_bits);
1563 tcgetattr (fd, &tty);
1605 cfsetispeed(&tty, spd);
1606 cfsetospeed(&tty, spd);
1608 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1609 |INLCR|IGNCR|ICRNL|IXON);
1610 tty.c_oflag |= OPOST;
1611 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1612 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS);
1633 tty.c_cflag |= PARENB;
1636 tty.c_cflag |= PARENB | PARODD;
1640 tcsetattr (fd, TCSANOW, &tty);
1643 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1645 FDCharDriver *s = chr->opaque;
1648 case CHR_IOCTL_SERIAL_SET_PARAMS:
1650 QEMUSerialSetParams *ssp = arg;
1651 tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
1652 ssp->data_bits, ssp->stop_bits);
1655 case CHR_IOCTL_SERIAL_SET_BREAK:
1657 int enable = *(int *)arg;
1659 tcsendbreak(s->fd_in, 1);
1668 CharDriverState *qemu_chr_open_tty(const char *filename)
1670 CharDriverState *chr;
1673 fd = open(filename, O_RDWR | O_NONBLOCK);
1676 fcntl(fd, F_SETFL, O_NONBLOCK);
1677 tty_serial_init(fd, 115200, 'N', 8, 1);
1678 chr = qemu_chr_open_fd(fd, fd);
1681 chr->chr_ioctl = tty_serial_ioctl;
1685 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1687 int fd = (int)chr->opaque;
1691 case CHR_IOCTL_PP_READ_DATA:
1692 if (ioctl(fd, PPRDATA, &b) < 0)
1694 *(uint8_t *)arg = b;
1696 case CHR_IOCTL_PP_WRITE_DATA:
1697 b = *(uint8_t *)arg;
1698 if (ioctl(fd, PPWDATA, &b) < 0)
1701 case CHR_IOCTL_PP_READ_CONTROL:
1702 if (ioctl(fd, PPRCONTROL, &b) < 0)
1704 *(uint8_t *)arg = b;
1706 case CHR_IOCTL_PP_WRITE_CONTROL:
1707 b = *(uint8_t *)arg;
1708 if (ioctl(fd, PPWCONTROL, &b) < 0)
1711 case CHR_IOCTL_PP_READ_STATUS:
1712 if (ioctl(fd, PPRSTATUS, &b) < 0)
1714 *(uint8_t *)arg = b;
1722 CharDriverState *qemu_chr_open_pp(const char *filename)
1724 CharDriverState *chr;
1727 fd = open(filename, O_RDWR);
1731 if (ioctl(fd, PPCLAIM) < 0) {
1736 chr = qemu_mallocz(sizeof(CharDriverState));
1741 chr->opaque = (void *)fd;
1742 chr->chr_write = null_chr_write;
1743 chr->chr_add_read_handler = null_chr_add_read_handler;
1744 chr->chr_ioctl = pp_ioctl;
1749 CharDriverState *qemu_chr_open_pty(void)
1755 #endif /* !defined(_WIN32) */
1759 IOCanRWHandler *fd_can_read;
1760 IOReadHandler *fd_read;
1763 HANDLE hcom, hrecv, hsend;
1764 OVERLAPPED orecv, osend;
1769 #define NSENDBUF 2048
1770 #define NRECVBUF 2048
1771 #define MAXCONNECT 1
1772 #define NTIMEOUT 5000
1774 static int win_chr_poll(void *opaque);
1775 static int win_chr_pipe_poll(void *opaque);
1777 static void win_chr_close2(WinCharState *s)
1780 CloseHandle(s->hsend);
1784 CloseHandle(s->hrecv);
1788 CloseHandle(s->hcom);
1792 qemu_del_polling_cb(win_chr_pipe_poll, s);
1794 qemu_del_polling_cb(win_chr_poll, s);
1797 static void win_chr_close(CharDriverState *chr)
1799 WinCharState *s = chr->opaque;
1803 static int win_chr_init(WinCharState *s, const char *filename)
1806 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
1811 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1813 fprintf(stderr, "Failed CreateEvent\n");
1816 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1818 fprintf(stderr, "Failed CreateEvent\n");
1822 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
1823 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
1824 if (s->hcom == INVALID_HANDLE_VALUE) {
1825 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
1830 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
1831 fprintf(stderr, "Failed SetupComm\n");
1835 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
1836 size = sizeof(COMMCONFIG);
1837 GetDefaultCommConfig(filename, &comcfg, &size);
1838 comcfg.dcb.DCBlength = sizeof(DCB);
1839 CommConfigDialog(filename, NULL, &comcfg);
1841 if (!SetCommState(s->hcom, &comcfg.dcb)) {
1842 fprintf(stderr, "Failed SetCommState\n");
1846 if (!SetCommMask(s->hcom, EV_ERR)) {
1847 fprintf(stderr, "Failed SetCommMask\n");
1851 cto.ReadIntervalTimeout = MAXDWORD;
1852 if (!SetCommTimeouts(s->hcom, &cto)) {
1853 fprintf(stderr, "Failed SetCommTimeouts\n");
1857 if (!ClearCommError(s->hcom, &err, &comstat)) {
1858 fprintf(stderr, "Failed ClearCommError\n");
1861 qemu_add_polling_cb(win_chr_poll, s);
1869 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
1871 WinCharState *s = chr->opaque;
1872 DWORD len, ret, size, err;
1875 ZeroMemory(&s->osend, sizeof(s->osend));
1876 s->osend.hEvent = s->hsend;
1879 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
1881 ret = WriteFile(s->hcom, buf, len, &size, NULL);
1883 err = GetLastError();
1884 if (err == ERROR_IO_PENDING) {
1885 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
1903 static int win_chr_read_poll(WinCharState *s)
1905 s->max_size = s->fd_can_read(s->win_opaque);
1909 static void win_chr_readfile(WinCharState *s)
1915 ZeroMemory(&s->orecv, sizeof(s->orecv));
1916 s->orecv.hEvent = s->hrecv;
1917 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
1919 err = GetLastError();
1920 if (err == ERROR_IO_PENDING) {
1921 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
1926 s->fd_read(s->win_opaque, buf, size);
1930 static void win_chr_read(WinCharState *s)
1932 if (s->len > s->max_size)
1933 s->len = s->max_size;
1937 win_chr_readfile(s);
1940 static int win_chr_poll(void *opaque)
1942 WinCharState *s = opaque;
1946 ClearCommError(s->hcom, &comerr, &status);
1947 if (status.cbInQue > 0) {
1948 s->len = status.cbInQue;
1949 win_chr_read_poll(s);
1956 static void win_chr_add_read_handler(CharDriverState *chr,
1957 IOCanRWHandler *fd_can_read,
1958 IOReadHandler *fd_read, void *opaque)
1960 WinCharState *s = chr->opaque;
1962 s->fd_can_read = fd_can_read;
1963 s->fd_read = fd_read;
1964 s->win_opaque = opaque;
1967 CharDriverState *qemu_chr_open_win(const char *filename)
1969 CharDriverState *chr;
1972 chr = qemu_mallocz(sizeof(CharDriverState));
1975 s = qemu_mallocz(sizeof(WinCharState));
1981 chr->chr_write = win_chr_write;
1982 chr->chr_add_read_handler = win_chr_add_read_handler;
1983 chr->chr_close = win_chr_close;
1985 if (win_chr_init(s, filename) < 0) {
1993 static int win_chr_pipe_poll(void *opaque)
1995 WinCharState *s = opaque;
1998 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
2001 win_chr_read_poll(s);
2008 static int win_chr_pipe_init(WinCharState *s, const char *filename)
2017 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2019 fprintf(stderr, "Failed CreateEvent\n");
2022 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2024 fprintf(stderr, "Failed CreateEvent\n");
2028 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
2029 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2030 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
2032 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2033 if (s->hcom == INVALID_HANDLE_VALUE) {
2034 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
2039 ZeroMemory(&ov, sizeof(ov));
2040 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2041 ret = ConnectNamedPipe(s->hcom, &ov);
2043 fprintf(stderr, "Failed ConnectNamedPipe\n");
2047 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2049 fprintf(stderr, "Failed GetOverlappedResult\n");
2051 CloseHandle(ov.hEvent);
2058 CloseHandle(ov.hEvent);
2061 qemu_add_polling_cb(win_chr_pipe_poll, s);
2070 CharDriverState *qemu_chr_open_win_pipe(const char *filename)
2072 CharDriverState *chr;
2075 chr = qemu_mallocz(sizeof(CharDriverState));
2078 s = qemu_mallocz(sizeof(WinCharState));
2084 chr->chr_write = win_chr_write;
2085 chr->chr_add_read_handler = win_chr_add_read_handler;
2086 chr->chr_close = win_chr_close;
2088 if (win_chr_pipe_init(s, filename) < 0) {
2096 CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
2098 CharDriverState *chr;
2101 chr = qemu_mallocz(sizeof(CharDriverState));
2104 s = qemu_mallocz(sizeof(WinCharState));
2111 chr->chr_write = win_chr_write;
2112 chr->chr_add_read_handler = win_chr_add_read_handler;
2116 CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
2120 fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
2121 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2122 if (fd_out == INVALID_HANDLE_VALUE)
2125 return qemu_chr_open_win_file(fd_out);
2129 /***********************************************************/
2130 /* UDP Net console */
2133 IOCanRWHandler *fd_can_read;
2134 IOReadHandler *fd_read;
2137 struct sockaddr_in daddr;
2144 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2146 NetCharDriver *s = chr->opaque;
2148 return sendto(s->fd, buf, len, 0,
2149 (struct sockaddr *)&s->daddr, sizeof(struct sockaddr_in));
2152 static int udp_chr_read_poll(void *opaque)
2154 CharDriverState *chr = opaque;
2155 NetCharDriver *s = chr->opaque;
2157 s->max_size = s->fd_can_read(s->fd_opaque);
2159 /* If there were any stray characters in the queue process them
2162 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2163 s->fd_read(s->fd_opaque, &s->buf[s->bufptr], 1);
2165 s->max_size = s->fd_can_read(s->fd_opaque);
2170 static void udp_chr_read(void *opaque)
2172 CharDriverState *chr = opaque;
2173 NetCharDriver *s = chr->opaque;
2175 if (s->max_size == 0)
2177 s->bufcnt = recv(s->fd, s->buf, sizeof(s->buf), 0);
2178 s->bufptr = s->bufcnt;
2183 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2184 s->fd_read(s->fd_opaque, &s->buf[s->bufptr], 1);
2186 s->max_size = s->fd_can_read(s->fd_opaque);
2190 static void udp_chr_add_read_handler(CharDriverState *chr,
2191 IOCanRWHandler *fd_can_read,
2192 IOReadHandler *fd_read, void *opaque)
2194 NetCharDriver *s = chr->opaque;
2197 s->fd_can_read = fd_can_read;
2198 s->fd_read = fd_read;
2199 s->fd_opaque = opaque;
2200 qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
2201 udp_chr_read, NULL, chr);
2205 int parse_host_port(struct sockaddr_in *saddr, const char *str);
2207 CharDriverState *qemu_chr_open_udp(const char *def)
2209 CharDriverState *chr = NULL;
2210 NetCharDriver *s = NULL;
2213 struct sockaddr_in addr;
2217 chr = qemu_mallocz(sizeof(CharDriverState));
2220 s = qemu_mallocz(sizeof(NetCharDriver));
2224 fd = socket(PF_INET, SOCK_DGRAM, 0);
2226 perror("socket(PF_INET, SOCK_DGRAM)");
2230 /* There are three types of port definitions
2231 * 1) udp:remote_port
2232 * Juse use 0.0.0.0 for the IP and send to remote
2233 * 2) udp:remote_host:port
2234 * Use a IP and send traffic to remote
2235 * 3) udp:local_port:remote_host:remote_port
2236 * Use local_port as the originator + #2
2240 while ((p = strchr(p, ':'))) {
2246 memset(&addr,0,sizeof(addr));
2247 addr.sin_family = AF_INET;
2248 addr.sin_addr.s_addr = htonl(INADDR_ANY);
2249 s->daddr.sin_family = AF_INET;
2250 s->daddr.sin_addr.s_addr = htonl(INADDR_ANY);
2254 port = strtol(p, (char **)&r, 0);
2256 fprintf(stderr, "Error parsing port number\n");
2259 s->daddr.sin_port = htons((short)port);
2262 port = strtol(p, (char **)&r, 0);
2264 fprintf(stderr, "Error parsing port number\n");
2267 addr.sin_port = htons((short)port);
2269 /* Fall through to case 1 now that we have the local port */
2271 if (parse_host_port(&s->daddr, p) < 0) {
2272 fprintf(stderr, "Error parsing host name and port\n");
2277 fprintf(stderr, "Too many ':' characters\n");
2281 if (bind(fd, (struct sockaddr *)&addr, sizeof(addr)) < 0)
2291 chr->chr_write = udp_chr_write;
2292 chr->chr_add_read_handler = udp_chr_add_read_handler;
2305 /***********************************************************/
2306 /* TCP Net console */
2309 IOCanRWHandler *fd_can_read;
2310 IOReadHandler *fd_read;
2317 static void tcp_chr_accept(void *opaque);
2319 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2321 TCPCharDriver *s = chr->opaque;
2323 return send_all(s->fd, buf, len);
2325 /* XXX: indicate an error ? */
2330 static int tcp_chr_read_poll(void *opaque)
2332 CharDriverState *chr = opaque;
2333 TCPCharDriver *s = chr->opaque;
2336 s->max_size = s->fd_can_read(s->fd_opaque);
2340 static void tcp_chr_read(void *opaque)
2342 CharDriverState *chr = opaque;
2343 TCPCharDriver *s = chr->opaque;
2347 if (!s->connected || s->max_size <= 0)
2350 if (len > s->max_size)
2352 size = recv(s->fd, buf, len, 0);
2354 /* connection closed */
2356 if (s->listen_fd >= 0) {
2357 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2359 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2362 } else if (size > 0) {
2363 s->fd_read(s->fd_opaque, buf, size);
2367 static void tcp_chr_add_read_handler(CharDriverState *chr,
2368 IOCanRWHandler *fd_can_read,
2369 IOReadHandler *fd_read, void *opaque)
2371 TCPCharDriver *s = chr->opaque;
2373 s->fd_can_read = fd_can_read;
2374 s->fd_read = fd_read;
2375 s->fd_opaque = opaque;
2378 static void tcp_chr_connect(void *opaque)
2380 CharDriverState *chr = opaque;
2381 TCPCharDriver *s = chr->opaque;
2384 qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
2385 tcp_chr_read, NULL, chr);
2388 static void tcp_chr_accept(void *opaque)
2390 CharDriverState *chr = opaque;
2391 TCPCharDriver *s = chr->opaque;
2392 struct sockaddr_in saddr;
2397 len = sizeof(saddr);
2398 fd = accept(s->listen_fd, (struct sockaddr *)&saddr, &len);
2399 if (fd < 0 && errno != EINTR) {
2401 } else if (fd >= 0) {
2405 socket_set_nonblock(fd);
2407 qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
2408 tcp_chr_connect(chr);
2411 static void tcp_chr_close(CharDriverState *chr)
2413 TCPCharDriver *s = chr->opaque;
2416 if (s->listen_fd >= 0)
2417 closesocket(s->listen_fd);
2421 static CharDriverState *qemu_chr_open_tcp(const char *host_str,
2424 CharDriverState *chr = NULL;
2425 TCPCharDriver *s = NULL;
2426 int fd = -1, ret, err, val;
2427 struct sockaddr_in saddr;
2429 if (parse_host_port(&saddr, host_str) < 0)
2432 chr = qemu_mallocz(sizeof(CharDriverState));
2435 s = qemu_mallocz(sizeof(TCPCharDriver));
2439 fd = socket(PF_INET, SOCK_STREAM, 0);
2442 socket_set_nonblock(fd);
2448 /* allow fast reuse */
2450 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
2452 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
2455 ret = listen(fd, 0);
2459 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2462 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
2464 err = socket_error();
2465 if (err == EINTR || err == EWOULDBLOCK) {
2466 } else if (err == EINPROGRESS) {
2478 tcp_chr_connect(chr);
2480 qemu_set_fd_handler(s->fd, NULL, tcp_chr_connect, chr);
2484 chr->chr_write = tcp_chr_write;
2485 chr->chr_add_read_handler = tcp_chr_add_read_handler;
2486 chr->chr_close = tcp_chr_close;
2496 CharDriverState *qemu_chr_open(const char *filename)
2500 if (!strcmp(filename, "vc")) {
2501 return text_console_init(&display_state);
2502 } else if (!strcmp(filename, "null")) {
2503 return qemu_chr_open_null();
2505 if (strstart(filename, "tcp:", &p)) {
2506 return qemu_chr_open_tcp(p, 0);
2508 if (strstart(filename, "tcpl:", &p)) {
2509 return qemu_chr_open_tcp(p, 1);
2511 if (strstart(filename, "udp:", &p)) {
2512 return qemu_chr_open_udp(p);
2515 if (strstart(filename, "file:", &p)) {
2516 return qemu_chr_open_file_out(p);
2517 } else if (strstart(filename, "pipe:", &p)) {
2518 return qemu_chr_open_pipe(p);
2519 } else if (!strcmp(filename, "pty")) {
2520 return qemu_chr_open_pty();
2521 } else if (!strcmp(filename, "stdio")) {
2522 return qemu_chr_open_stdio();
2525 #if defined(__linux__)
2526 if (strstart(filename, "/dev/parport", NULL)) {
2527 return qemu_chr_open_pp(filename);
2529 if (strstart(filename, "/dev/", NULL)) {
2530 return qemu_chr_open_tty(filename);
2534 if (strstart(filename, "COM", NULL)) {
2535 return qemu_chr_open_win(filename);
2537 if (strstart(filename, "pipe:", &p)) {
2538 return qemu_chr_open_win_pipe(p);
2540 if (strstart(filename, "file:", &p)) {
2541 return qemu_chr_open_win_file_out(p);
2549 void qemu_chr_close(CharDriverState *chr)
2552 chr->chr_close(chr);
2555 /***********************************************************/
2556 /* network device redirectors */
2558 void hex_dump(FILE *f, const uint8_t *buf, int size)
2562 for(i=0;i<size;i+=16) {
2566 fprintf(f, "%08x ", i);
2569 fprintf(f, " %02x", buf[i+j]);
2574 for(j=0;j<len;j++) {
2576 if (c < ' ' || c > '~')
2578 fprintf(f, "%c", c);
2584 static int parse_macaddr(uint8_t *macaddr, const char *p)
2587 for(i = 0; i < 6; i++) {
2588 macaddr[i] = strtol(p, (char **)&p, 16);
2601 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
2606 p1 = strchr(p, sep);
2612 if (len > buf_size - 1)
2614 memcpy(buf, p, len);
2621 int parse_host_port(struct sockaddr_in *saddr, const char *str)
2629 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2631 saddr->sin_family = AF_INET;
2632 if (buf[0] == '\0') {
2633 saddr->sin_addr.s_addr = 0;
2635 if (isdigit(buf[0])) {
2636 if (!inet_aton(buf, &saddr->sin_addr))
2639 if ((he = gethostbyname(buf)) == NULL)
2641 saddr->sin_addr = *(struct in_addr *)he->h_addr;
2644 port = strtol(p, (char **)&r, 0);
2647 saddr->sin_port = htons(port);
2651 /* find or alloc a new VLAN */
2652 VLANState *qemu_find_vlan(int id)
2654 VLANState **pvlan, *vlan;
2655 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
2659 vlan = qemu_mallocz(sizeof(VLANState));
2664 pvlan = &first_vlan;
2665 while (*pvlan != NULL)
2666 pvlan = &(*pvlan)->next;
2671 VLANClientState *qemu_new_vlan_client(VLANState *vlan,
2672 IOReadHandler *fd_read,
2673 IOCanRWHandler *fd_can_read,
2676 VLANClientState *vc, **pvc;
2677 vc = qemu_mallocz(sizeof(VLANClientState));
2680 vc->fd_read = fd_read;
2681 vc->fd_can_read = fd_can_read;
2682 vc->opaque = opaque;
2686 pvc = &vlan->first_client;
2687 while (*pvc != NULL)
2688 pvc = &(*pvc)->next;
2693 int qemu_can_send_packet(VLANClientState *vc1)
2695 VLANState *vlan = vc1->vlan;
2696 VLANClientState *vc;
2698 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
2700 if (vc->fd_can_read && !vc->fd_can_read(vc->opaque))
2707 void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
2709 VLANState *vlan = vc1->vlan;
2710 VLANClientState *vc;
2713 printf("vlan %d send:\n", vlan->id);
2714 hex_dump(stdout, buf, size);
2716 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
2718 vc->fd_read(vc->opaque, buf, size);
2723 #if defined(CONFIG_SLIRP)
2725 /* slirp network adapter */
2727 static int slirp_inited;
2728 static VLANClientState *slirp_vc;
2730 int slirp_can_output(void)
2732 return !slirp_vc || qemu_can_send_packet(slirp_vc);
2735 void slirp_output(const uint8_t *pkt, int pkt_len)
2738 printf("slirp output:\n");
2739 hex_dump(stdout, pkt, pkt_len);
2743 qemu_send_packet(slirp_vc, pkt, pkt_len);
2746 static void slirp_receive(void *opaque, const uint8_t *buf, int size)
2749 printf("slirp input:\n");
2750 hex_dump(stdout, buf, size);
2752 slirp_input(buf, size);
2755 static int net_slirp_init(VLANState *vlan)
2757 if (!slirp_inited) {
2761 slirp_vc = qemu_new_vlan_client(vlan,
2762 slirp_receive, NULL, NULL);
2763 snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
2767 static void net_slirp_redir(const char *redir_str)
2772 struct in_addr guest_addr;
2773 int host_port, guest_port;
2775 if (!slirp_inited) {
2781 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2783 if (!strcmp(buf, "tcp")) {
2785 } else if (!strcmp(buf, "udp")) {
2791 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2793 host_port = strtol(buf, &r, 0);
2797 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2799 if (buf[0] == '\0') {
2800 pstrcpy(buf, sizeof(buf), "10.0.2.15");
2802 if (!inet_aton(buf, &guest_addr))
2805 guest_port = strtol(p, &r, 0);
2809 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
2810 fprintf(stderr, "qemu: could not set up redirection\n");
2815 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
2823 static void smb_exit(void)
2827 char filename[1024];
2829 /* erase all the files in the directory */
2830 d = opendir(smb_dir);
2835 if (strcmp(de->d_name, ".") != 0 &&
2836 strcmp(de->d_name, "..") != 0) {
2837 snprintf(filename, sizeof(filename), "%s/%s",
2838 smb_dir, de->d_name);
2846 /* automatic user mode samba server configuration */
2847 void net_slirp_smb(const char *exported_dir)
2849 char smb_conf[1024];
2850 char smb_cmdline[1024];
2853 if (!slirp_inited) {
2858 /* XXX: better tmp dir construction */
2859 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
2860 if (mkdir(smb_dir, 0700) < 0) {
2861 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
2864 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
2866 f = fopen(smb_conf, "w");
2868 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
2875 "socket address=127.0.0.1\n"
2876 "pid directory=%s\n"
2877 "lock directory=%s\n"
2878 "log file=%s/log.smbd\n"
2879 "smb passwd file=%s/smbpasswd\n"
2880 "security = share\n"
2895 snprintf(smb_cmdline, sizeof(smb_cmdline), "/usr/sbin/smbd -s %s",
2898 slirp_add_exec(0, smb_cmdline, 4, 139);
2901 #endif /* !defined(_WIN32) */
2903 #endif /* CONFIG_SLIRP */
2905 #if !defined(_WIN32)
2907 typedef struct TAPState {
2908 VLANClientState *vc;
2912 static void tap_receive(void *opaque, const uint8_t *buf, int size)
2914 TAPState *s = opaque;
2917 ret = write(s->fd, buf, size);
2918 if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
2925 static void tap_send(void *opaque)
2927 TAPState *s = opaque;
2931 size = read(s->fd, buf, sizeof(buf));
2933 qemu_send_packet(s->vc, buf, size);
2939 static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
2943 s = qemu_mallocz(sizeof(TAPState));
2947 s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
2948 qemu_set_fd_handler(s->fd, tap_send, NULL, s);
2949 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
2954 static int tap_open(char *ifname, int ifname_size)
2960 fd = open("/dev/tap", O_RDWR);
2962 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
2967 dev = devname(s.st_rdev, S_IFCHR);
2968 pstrcpy(ifname, ifname_size, dev);
2970 fcntl(fd, F_SETFL, O_NONBLOCK);
2973 #elif defined(__sun__)
2974 static int tap_open(char *ifname, int ifname_size)
2976 fprintf(stderr, "warning: tap_open not yet implemented\n");
2980 static int tap_open(char *ifname, int ifname_size)
2985 fd = open("/dev/net/tun", O_RDWR);
2987 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
2990 memset(&ifr, 0, sizeof(ifr));
2991 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
2992 if (ifname[0] != '\0')
2993 pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
2995 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
2996 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
2998 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
3002 pstrcpy(ifname, ifname_size, ifr.ifr_name);
3003 fcntl(fd, F_SETFL, O_NONBLOCK);
3008 static int net_tap_init(VLANState *vlan, const char *ifname1,
3009 const char *setup_script)
3012 int pid, status, fd;
3017 if (ifname1 != NULL)
3018 pstrcpy(ifname, sizeof(ifname), ifname1);
3021 fd = tap_open(ifname, sizeof(ifname));
3027 if (setup_script[0] != '\0') {
3028 /* try to launch network init script */
3033 *parg++ = (char *)setup_script;
3036 execv(setup_script, args);
3039 while (waitpid(pid, &status, 0) != pid);
3040 if (!WIFEXITED(status) ||
3041 WEXITSTATUS(status) != 0) {
3042 fprintf(stderr, "%s: could not launch network script\n",
3048 s = net_tap_fd_init(vlan, fd);
3051 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3052 "tap: ifname=%s setup_script=%s", ifname, setup_script);
3056 #endif /* !_WIN32 */
3058 /* network connection */
3059 typedef struct NetSocketState {
3060 VLANClientState *vc;
3062 int state; /* 0 = getting length, 1 = getting data */
3066 struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
3069 typedef struct NetSocketListenState {
3072 } NetSocketListenState;
3074 /* XXX: we consider we can send the whole packet without blocking */
3075 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
3077 NetSocketState *s = opaque;
3081 send_all(s->fd, (const uint8_t *)&len, sizeof(len));
3082 send_all(s->fd, buf, size);
3085 static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
3087 NetSocketState *s = opaque;
3088 sendto(s->fd, buf, size, 0,
3089 (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
3092 static void net_socket_send(void *opaque)
3094 NetSocketState *s = opaque;
3099 size = recv(s->fd, buf1, sizeof(buf1), 0);
3101 err = socket_error();
3102 if (err != EWOULDBLOCK)
3104 } else if (size == 0) {
3105 /* end of connection */
3107 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3113 /* reassemble a packet from the network */
3119 memcpy(s->buf + s->index, buf, l);
3123 if (s->index == 4) {
3125 s->packet_len = ntohl(*(uint32_t *)s->buf);
3131 l = s->packet_len - s->index;
3134 memcpy(s->buf + s->index, buf, l);
3138 if (s->index >= s->packet_len) {
3139 qemu_send_packet(s->vc, s->buf, s->packet_len);
3148 static void net_socket_send_dgram(void *opaque)
3150 NetSocketState *s = opaque;
3153 size = recv(s->fd, s->buf, sizeof(s->buf), 0);
3157 /* end of connection */
3158 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3161 qemu_send_packet(s->vc, s->buf, size);
3164 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
3169 if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
3170 fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
3171 inet_ntoa(mcastaddr->sin_addr),
3172 (int)ntohl(mcastaddr->sin_addr.s_addr));
3176 fd = socket(PF_INET, SOCK_DGRAM, 0);
3178 perror("socket(PF_INET, SOCK_DGRAM)");
3183 ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
3184 (const char *)&val, sizeof(val));
3186 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
3190 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
3196 /* Add host to multicast group */
3197 imr.imr_multiaddr = mcastaddr->sin_addr;
3198 imr.imr_interface.s_addr = htonl(INADDR_ANY);
3200 ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
3201 (const char *)&imr, sizeof(struct ip_mreq));
3203 perror("setsockopt(IP_ADD_MEMBERSHIP)");
3207 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
3209 ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
3210 (const char *)&val, sizeof(val));
3212 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
3216 socket_set_nonblock(fd);
3224 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd,
3227 struct sockaddr_in saddr;
3229 socklen_t saddr_len;
3232 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
3233 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
3234 * by ONLY ONE process: we must "clone" this dgram socket --jjo
3238 if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
3240 if (saddr.sin_addr.s_addr==0) {
3241 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
3245 /* clone dgram socket */
3246 newfd = net_socket_mcast_create(&saddr);
3248 /* error already reported by net_socket_mcast_create() */
3252 /* clone newfd to fd, close newfd */
3257 fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
3258 fd, strerror(errno));
3263 s = qemu_mallocz(sizeof(NetSocketState));
3268 s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
3269 qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
3271 /* mcast: save bound address as dst */
3272 if (is_connected) s->dgram_dst=saddr;
3274 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3275 "socket: fd=%d (%s mcast=%s:%d)",
3276 fd, is_connected? "cloned" : "",
3277 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3281 static void net_socket_connect(void *opaque)
3283 NetSocketState *s = opaque;
3284 qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
3287 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd,
3291 s = qemu_mallocz(sizeof(NetSocketState));
3295 s->vc = qemu_new_vlan_client(vlan,
3296 net_socket_receive, NULL, s);
3297 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3298 "socket: fd=%d", fd);
3300 net_socket_connect(s);
3302 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
3307 static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
3310 int so_type=-1, optlen=sizeof(so_type);
3312 if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type, &optlen)< 0) {
3313 fprintf(stderr, "qemu: error: setsockopt(SO_TYPE) for fd=%d failed\n", fd);
3318 return net_socket_fd_init_dgram(vlan, fd, is_connected);
3320 return net_socket_fd_init_stream(vlan, fd, is_connected);
3322 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
3323 fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
3324 return net_socket_fd_init_stream(vlan, fd, is_connected);
3329 static void net_socket_accept(void *opaque)
3331 NetSocketListenState *s = opaque;
3333 struct sockaddr_in saddr;
3338 len = sizeof(saddr);
3339 fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
3340 if (fd < 0 && errno != EINTR) {
3342 } else if (fd >= 0) {
3346 s1 = net_socket_fd_init(s->vlan, fd, 1);
3350 snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
3351 "socket: connection from %s:%d",
3352 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3356 static int net_socket_listen_init(VLANState *vlan, const char *host_str)
3358 NetSocketListenState *s;
3360 struct sockaddr_in saddr;
3362 if (parse_host_port(&saddr, host_str) < 0)
3365 s = qemu_mallocz(sizeof(NetSocketListenState));
3369 fd = socket(PF_INET, SOCK_STREAM, 0);
3374 socket_set_nonblock(fd);
3376 /* allow fast reuse */
3378 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
3380 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
3385 ret = listen(fd, 0);
3392 qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
3396 static int net_socket_connect_init(VLANState *vlan, const char *host_str)
3399 int fd, connected, ret, err;
3400 struct sockaddr_in saddr;
3402 if (parse_host_port(&saddr, host_str) < 0)
3405 fd = socket(PF_INET, SOCK_STREAM, 0);
3410 socket_set_nonblock(fd);
3414 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
3416 err = socket_error();
3417 if (err == EINTR || err == EWOULDBLOCK) {
3418 } else if (err == EINPROGRESS) {
3430 s = net_socket_fd_init(vlan, fd, connected);
3433 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3434 "socket: connect to %s:%d",
3435 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3439 static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
3443 struct sockaddr_in saddr;
3445 if (parse_host_port(&saddr, host_str) < 0)
3449 fd = net_socket_mcast_create(&saddr);
3453 s = net_socket_fd_init(vlan, fd, 0);
3457 s->dgram_dst = saddr;
3459 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3460 "socket: mcast=%s:%d",
3461 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3466 static int get_param_value(char *buf, int buf_size,
3467 const char *tag, const char *str)
3476 while (*p != '\0' && *p != '=') {
3477 if ((q - option) < sizeof(option) - 1)
3485 if (!strcmp(tag, option)) {
3487 while (*p != '\0' && *p != ',') {
3488 if ((q - buf) < buf_size - 1)
3495 while (*p != '\0' && *p != ',') {
3506 int net_client_init(const char *str)
3517 while (*p != '\0' && *p != ',') {
3518 if ((q - device) < sizeof(device) - 1)
3526 if (get_param_value(buf, sizeof(buf), "vlan", p)) {
3527 vlan_id = strtol(buf, NULL, 0);
3529 vlan = qemu_find_vlan(vlan_id);
3531 fprintf(stderr, "Could not create vlan %d\n", vlan_id);
3534 if (!strcmp(device, "nic")) {
3538 if (nb_nics >= MAX_NICS) {
3539 fprintf(stderr, "Too Many NICs\n");
3542 nd = &nd_table[nb_nics];
3543 macaddr = nd->macaddr;
3549 macaddr[5] = 0x56 + nb_nics;
3551 if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
3552 if (parse_macaddr(macaddr, buf) < 0) {
3553 fprintf(stderr, "invalid syntax for ethernet address\n");
3557 if (get_param_value(buf, sizeof(buf), "model", p)) {
3558 nd->model = strdup(buf);
3564 if (!strcmp(device, "none")) {
3565 /* does nothing. It is needed to signal that no network cards
3570 if (!strcmp(device, "user")) {
3571 if (get_param_value(buf, sizeof(buf), "hostname", p)) {
3572 pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
3574 ret = net_slirp_init(vlan);
3578 if (!strcmp(device, "tap")) {
3580 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
3581 fprintf(stderr, "tap: no interface name\n");
3584 ret = tap_win32_init(vlan, ifname);
3587 if (!strcmp(device, "tap")) {
3589 char setup_script[1024];
3591 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
3592 fd = strtol(buf, NULL, 0);
3594 if (net_tap_fd_init(vlan, fd))
3597 get_param_value(ifname, sizeof(ifname), "ifname", p);
3598 if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
3599 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
3601 ret = net_tap_init(vlan, ifname, setup_script);
3605 if (!strcmp(device, "socket")) {
3606 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
3608 fd = strtol(buf, NULL, 0);
3610 if (net_socket_fd_init(vlan, fd, 1))
3612 } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
3613 ret = net_socket_listen_init(vlan, buf);
3614 } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
3615 ret = net_socket_connect_init(vlan, buf);
3616 } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
3617 ret = net_socket_mcast_init(vlan, buf);
3619 fprintf(stderr, "Unknown socket options: %s\n", p);
3624 fprintf(stderr, "Unknown network device: %s\n", device);
3628 fprintf(stderr, "Could not initialize device '%s'\n", device);
3634 void do_info_network(void)
3637 VLANClientState *vc;
3639 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
3640 term_printf("VLAN %d devices:\n", vlan->id);
3641 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
3642 term_printf(" %s\n", vc->info_str);
3646 /***********************************************************/
3649 static USBPort *used_usb_ports;
3650 static USBPort *free_usb_ports;
3652 /* ??? Maybe change this to register a hub to keep track of the topology. */
3653 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
3654 usb_attachfn attach)
3656 port->opaque = opaque;
3657 port->index = index;
3658 port->attach = attach;
3659 port->next = free_usb_ports;
3660 free_usb_ports = port;
3663 static int usb_device_add(const char *devname)
3669 if (!free_usb_ports)
3672 if (strstart(devname, "host:", &p)) {
3673 dev = usb_host_device_open(p);
3674 } else if (!strcmp(devname, "mouse")) {
3675 dev = usb_mouse_init();
3676 } else if (!strcmp(devname, "tablet")) {
3677 dev = usb_tablet_init();
3678 } else if (strstart(devname, "disk:", &p)) {
3679 dev = usb_msd_init(p);
3686 /* Find a USB port to add the device to. */
3687 port = free_usb_ports;
3691 /* Create a new hub and chain it on. */
3692 free_usb_ports = NULL;
3693 port->next = used_usb_ports;
3694 used_usb_ports = port;
3696 hub = usb_hub_init(VM_USB_HUB_SIZE);
3697 usb_attach(port, hub);
3698 port = free_usb_ports;
3701 free_usb_ports = port->next;
3702 port->next = used_usb_ports;
3703 used_usb_ports = port;
3704 usb_attach(port, dev);
3708 static int usb_device_del(const char *devname)
3715 if (!used_usb_ports)
3718 p = strchr(devname, '.');
3721 bus_num = strtoul(devname, NULL, 0);
3722 addr = strtoul(p + 1, NULL, 0);
3726 lastp = &used_usb_ports;
3727 port = used_usb_ports;
3728 while (port && port->dev->addr != addr) {
3729 lastp = &port->next;
3736 *lastp = port->next;
3737 usb_attach(port, NULL);
3738 port->next = free_usb_ports;
3739 free_usb_ports = port;
3743 void do_usb_add(const char *devname)
3746 ret = usb_device_add(devname);
3748 term_printf("Could not add USB device '%s'\n", devname);
3751 void do_usb_del(const char *devname)
3754 ret = usb_device_del(devname);
3756 term_printf("Could not remove USB device '%s'\n", devname);
3763 const char *speed_str;
3766 term_printf("USB support not enabled\n");
3770 for (port = used_usb_ports; port; port = port->next) {
3774 switch(dev->speed) {
3778 case USB_SPEED_FULL:
3781 case USB_SPEED_HIGH:
3788 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
3789 0, dev->addr, speed_str, dev->devname);
3793 /***********************************************************/
3796 static char *pid_filename;
3798 /* Remove PID file. Called on normal exit */
3800 static void remove_pidfile(void)
3802 unlink (pid_filename);
3805 static void create_pidfile(const char *filename)
3807 struct stat pidstat;
3810 /* Try to write our PID to the named file */
3811 if (stat(filename, &pidstat) < 0) {
3812 if (errno == ENOENT) {
3813 if ((f = fopen (filename, "w")) == NULL) {
3814 perror("Opening pidfile");
3817 fprintf(f, "%d\n", getpid());
3819 pid_filename = qemu_strdup(filename);
3820 if (!pid_filename) {
3821 fprintf(stderr, "Could not save PID filename");
3824 atexit(remove_pidfile);
3827 fprintf(stderr, "%s already exists. Remove it and try again.\n",
3833 /***********************************************************/
3836 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
3840 static void dumb_resize(DisplayState *ds, int w, int h)
3844 static void dumb_refresh(DisplayState *ds)
3849 void dumb_display_init(DisplayState *ds)
3854 ds->dpy_update = dumb_update;
3855 ds->dpy_resize = dumb_resize;
3856 ds->dpy_refresh = dumb_refresh;
3859 /***********************************************************/
3862 #define MAX_IO_HANDLERS 64
3864 typedef struct IOHandlerRecord {
3866 IOCanRWHandler *fd_read_poll;
3868 IOHandler *fd_write;
3870 /* temporary data */
3872 struct IOHandlerRecord *next;
3875 static IOHandlerRecord *first_io_handler;
3877 /* XXX: fd_read_poll should be suppressed, but an API change is
3878 necessary in the character devices to suppress fd_can_read(). */
3879 int qemu_set_fd_handler2(int fd,
3880 IOCanRWHandler *fd_read_poll,
3882 IOHandler *fd_write,
3885 IOHandlerRecord **pioh, *ioh;
3887 if (!fd_read && !fd_write) {
3888 pioh = &first_io_handler;
3893 if (ioh->fd == fd) {
3901 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3905 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
3908 ioh->next = first_io_handler;
3909 first_io_handler = ioh;
3912 ioh->fd_read_poll = fd_read_poll;
3913 ioh->fd_read = fd_read;
3914 ioh->fd_write = fd_write;
3915 ioh->opaque = opaque;
3920 int qemu_set_fd_handler(int fd,
3922 IOHandler *fd_write,
3925 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
3928 /***********************************************************/
3929 /* Polling handling */
3931 typedef struct PollingEntry {
3934 struct PollingEntry *next;
3937 static PollingEntry *first_polling_entry;
3939 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
3941 PollingEntry **ppe, *pe;
3942 pe = qemu_mallocz(sizeof(PollingEntry));
3946 pe->opaque = opaque;
3947 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
3952 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
3954 PollingEntry **ppe, *pe;
3955 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
3957 if (pe->func == func && pe->opaque == opaque) {
3966 /***********************************************************/
3967 /* Wait objects support */
3968 typedef struct WaitObjects {
3970 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
3971 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
3972 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
3975 static WaitObjects wait_objects = {0};
3977 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
3979 WaitObjects *w = &wait_objects;
3981 if (w->num >= MAXIMUM_WAIT_OBJECTS)
3983 w->events[w->num] = handle;
3984 w->func[w->num] = func;
3985 w->opaque[w->num] = opaque;
3990 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
3993 WaitObjects *w = &wait_objects;
3996 for (i = 0; i < w->num; i++) {
3997 if (w->events[i] == handle)
4000 w->events[i] = w->events[i + 1];
4001 w->func[i] = w->func[i + 1];
4002 w->opaque[i] = w->opaque[i + 1];
4010 /***********************************************************/
4011 /* savevm/loadvm support */
4013 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
4015 fwrite(buf, 1, size, f);
4018 void qemu_put_byte(QEMUFile *f, int v)
4023 void qemu_put_be16(QEMUFile *f, unsigned int v)
4025 qemu_put_byte(f, v >> 8);
4026 qemu_put_byte(f, v);
4029 void qemu_put_be32(QEMUFile *f, unsigned int v)
4031 qemu_put_byte(f, v >> 24);
4032 qemu_put_byte(f, v >> 16);
4033 qemu_put_byte(f, v >> 8);
4034 qemu_put_byte(f, v);
4037 void qemu_put_be64(QEMUFile *f, uint64_t v)
4039 qemu_put_be32(f, v >> 32);
4040 qemu_put_be32(f, v);
4043 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size)
4045 return fread(buf, 1, size, f);
4048 int qemu_get_byte(QEMUFile *f)
4058 unsigned int qemu_get_be16(QEMUFile *f)
4061 v = qemu_get_byte(f) << 8;
4062 v |= qemu_get_byte(f);
4066 unsigned int qemu_get_be32(QEMUFile *f)
4069 v = qemu_get_byte(f) << 24;
4070 v |= qemu_get_byte(f) << 16;
4071 v |= qemu_get_byte(f) << 8;
4072 v |= qemu_get_byte(f);
4076 uint64_t qemu_get_be64(QEMUFile *f)
4079 v = (uint64_t)qemu_get_be32(f) << 32;
4080 v |= qemu_get_be32(f);
4084 int64_t qemu_ftell(QEMUFile *f)
4089 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
4091 if (fseek(f, pos, whence) < 0)
4096 typedef struct SaveStateEntry {
4100 SaveStateHandler *save_state;
4101 LoadStateHandler *load_state;
4103 struct SaveStateEntry *next;
4106 static SaveStateEntry *first_se;
4108 int register_savevm(const char *idstr,
4111 SaveStateHandler *save_state,
4112 LoadStateHandler *load_state,
4115 SaveStateEntry *se, **pse;
4117 se = qemu_malloc(sizeof(SaveStateEntry));
4120 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
4121 se->instance_id = instance_id;
4122 se->version_id = version_id;
4123 se->save_state = save_state;
4124 se->load_state = load_state;
4125 se->opaque = opaque;
4128 /* add at the end of list */
4130 while (*pse != NULL)
4131 pse = &(*pse)->next;
4136 #define QEMU_VM_FILE_MAGIC 0x5145564d
4137 #define QEMU_VM_FILE_VERSION 0x00000001
4139 int qemu_savevm(const char *filename)
4143 int len, len_pos, cur_pos, saved_vm_running, ret;
4145 saved_vm_running = vm_running;
4148 f = fopen(filename, "wb");
4154 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
4155 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
4157 for(se = first_se; se != NULL; se = se->next) {
4159 len = strlen(se->idstr);
4160 qemu_put_byte(f, len);
4161 qemu_put_buffer(f, se->idstr, len);
4163 qemu_put_be32(f, se->instance_id);
4164 qemu_put_be32(f, se->version_id);
4166 /* record size: filled later */
4168 qemu_put_be32(f, 0);
4170 se->save_state(f, se->opaque);
4172 /* fill record size */
4174 len = ftell(f) - len_pos - 4;
4175 fseek(f, len_pos, SEEK_SET);
4176 qemu_put_be32(f, len);
4177 fseek(f, cur_pos, SEEK_SET);
4183 if (saved_vm_running)
4188 static SaveStateEntry *find_se(const char *idstr, int instance_id)
4192 for(se = first_se; se != NULL; se = se->next) {
4193 if (!strcmp(se->idstr, idstr) &&
4194 instance_id == se->instance_id)
4200 int qemu_loadvm(const char *filename)
4204 int len, cur_pos, ret, instance_id, record_len, version_id;
4205 int saved_vm_running;
4209 saved_vm_running = vm_running;
4212 f = fopen(filename, "rb");
4218 v = qemu_get_be32(f);
4219 if (v != QEMU_VM_FILE_MAGIC)
4221 v = qemu_get_be32(f);
4222 if (v != QEMU_VM_FILE_VERSION) {
4229 len = qemu_get_byte(f);
4232 qemu_get_buffer(f, idstr, len);
4234 instance_id = qemu_get_be32(f);
4235 version_id = qemu_get_be32(f);
4236 record_len = qemu_get_be32(f);
4238 printf("idstr=%s instance=0x%x version=%d len=%d\n",
4239 idstr, instance_id, version_id, record_len);
4242 se = find_se(idstr, instance_id);
4244 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
4245 instance_id, idstr);
4247 ret = se->load_state(f, se->opaque, version_id);
4249 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
4250 instance_id, idstr);
4253 /* always seek to exact end of record */
4254 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
4259 if (saved_vm_running)
4264 /***********************************************************/
4265 /* cpu save/restore */
4267 #if defined(TARGET_I386)
4269 static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
4271 qemu_put_be32(f, dt->selector);
4272 qemu_put_betl(f, dt->base);
4273 qemu_put_be32(f, dt->limit);
4274 qemu_put_be32(f, dt->flags);
4277 static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
4279 dt->selector = qemu_get_be32(f);
4280 dt->base = qemu_get_betl(f);
4281 dt->limit = qemu_get_be32(f);
4282 dt->flags = qemu_get_be32(f);
4285 void cpu_save(QEMUFile *f, void *opaque)
4287 CPUState *env = opaque;
4288 uint16_t fptag, fpus, fpuc, fpregs_format;
4292 for(i = 0; i < CPU_NB_REGS; i++)
4293 qemu_put_betls(f, &env->regs[i]);
4294 qemu_put_betls(f, &env->eip);
4295 qemu_put_betls(f, &env->eflags);
4296 hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
4297 qemu_put_be32s(f, &hflags);
4301 fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
4303 for(i = 0; i < 8; i++) {
4304 fptag |= ((!env->fptags[i]) << i);
4307 qemu_put_be16s(f, &fpuc);
4308 qemu_put_be16s(f, &fpus);
4309 qemu_put_be16s(f, &fptag);
4311 #ifdef USE_X86LDOUBLE
4316 qemu_put_be16s(f, &fpregs_format);
4318 for(i = 0; i < 8; i++) {
4319 #ifdef USE_X86LDOUBLE
4323 /* we save the real CPU data (in case of MMX usage only 'mant'
4324 contains the MMX register */
4325 cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
4326 qemu_put_be64(f, mant);
4327 qemu_put_be16(f, exp);
4330 /* if we use doubles for float emulation, we save the doubles to
4331 avoid losing information in case of MMX usage. It can give
4332 problems if the image is restored on a CPU where long
4333 doubles are used instead. */
4334 qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
4338 for(i = 0; i < 6; i++)
4339 cpu_put_seg(f, &env->segs[i]);
4340 cpu_put_seg(f, &env->ldt);
4341 cpu_put_seg(f, &env->tr);
4342 cpu_put_seg(f, &env->gdt);
4343 cpu_put_seg(f, &env->idt);
4345 qemu_put_be32s(f, &env->sysenter_cs);
4346 qemu_put_be32s(f, &env->sysenter_esp);
4347 qemu_put_be32s(f, &env->sysenter_eip);
4349 qemu_put_betls(f, &env->cr[0]);
4350 qemu_put_betls(f, &env->cr[2]);
4351 qemu_put_betls(f, &env->cr[3]);
4352 qemu_put_betls(f, &env->cr[4]);
4354 for(i = 0; i < 8; i++)
4355 qemu_put_betls(f, &env->dr[i]);
4358 qemu_put_be32s(f, &env->a20_mask);
4361 qemu_put_be32s(f, &env->mxcsr);
4362 for(i = 0; i < CPU_NB_REGS; i++) {
4363 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
4364 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
4367 #ifdef TARGET_X86_64
4368 qemu_put_be64s(f, &env->efer);
4369 qemu_put_be64s(f, &env->star);
4370 qemu_put_be64s(f, &env->lstar);
4371 qemu_put_be64s(f, &env->cstar);
4372 qemu_put_be64s(f, &env->fmask);
4373 qemu_put_be64s(f, &env->kernelgsbase);
4377 #ifdef USE_X86LDOUBLE
4378 /* XXX: add that in a FPU generic layer */
4379 union x86_longdouble {
4384 #define MANTD1(fp) (fp & ((1LL << 52) - 1))
4385 #define EXPBIAS1 1023
4386 #define EXPD1(fp) ((fp >> 52) & 0x7FF)
4387 #define SIGND1(fp) ((fp >> 32) & 0x80000000)
4389 static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
4393 p->mant = (MANTD1(temp) << 11) | (1LL << 63);
4394 /* exponent + sign */
4395 e = EXPD1(temp) - EXPBIAS1 + 16383;
4396 e |= SIGND1(temp) >> 16;
4401 int cpu_load(QEMUFile *f, void *opaque, int version_id)
4403 CPUState *env = opaque;
4406 uint16_t fpus, fpuc, fptag, fpregs_format;
4408 if (version_id != 3)
4410 for(i = 0; i < CPU_NB_REGS; i++)
4411 qemu_get_betls(f, &env->regs[i]);
4412 qemu_get_betls(f, &env->eip);
4413 qemu_get_betls(f, &env->eflags);
4414 qemu_get_be32s(f, &hflags);
4416 qemu_get_be16s(f, &fpuc);
4417 qemu_get_be16s(f, &fpus);
4418 qemu_get_be16s(f, &fptag);
4419 qemu_get_be16s(f, &fpregs_format);
4421 /* NOTE: we cannot always restore the FPU state if the image come
4422 from a host with a different 'USE_X86LDOUBLE' define. We guess
4423 if we are in an MMX state to restore correctly in that case. */
4424 guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
4425 for(i = 0; i < 8; i++) {
4429 switch(fpregs_format) {
4431 mant = qemu_get_be64(f);
4432 exp = qemu_get_be16(f);
4433 #ifdef USE_X86LDOUBLE
4434 env->fpregs[i].d = cpu_set_fp80(mant, exp);
4436 /* difficult case */
4438 env->fpregs[i].mmx.MMX_Q(0) = mant;
4440 env->fpregs[i].d = cpu_set_fp80(mant, exp);
4444 mant = qemu_get_be64(f);
4445 #ifdef USE_X86LDOUBLE
4447 union x86_longdouble *p;
4448 /* difficult case */
4449 p = (void *)&env->fpregs[i];
4454 fp64_to_fp80(p, mant);
4458 env->fpregs[i].mmx.MMX_Q(0) = mant;
4467 /* XXX: restore FPU round state */
4468 env->fpstt = (fpus >> 11) & 7;
4469 env->fpus = fpus & ~0x3800;
4471 for(i = 0; i < 8; i++) {
4472 env->fptags[i] = (fptag >> i) & 1;
4475 for(i = 0; i < 6; i++)
4476 cpu_get_seg(f, &env->segs[i]);
4477 cpu_get_seg(f, &env->ldt);
4478 cpu_get_seg(f, &env->tr);
4479 cpu_get_seg(f, &env->gdt);
4480 cpu_get_seg(f, &env->idt);
4482 qemu_get_be32s(f, &env->sysenter_cs);
4483 qemu_get_be32s(f, &env->sysenter_esp);
4484 qemu_get_be32s(f, &env->sysenter_eip);
4486 qemu_get_betls(f, &env->cr[0]);
4487 qemu_get_betls(f, &env->cr[2]);
4488 qemu_get_betls(f, &env->cr[3]);
4489 qemu_get_betls(f, &env->cr[4]);
4491 for(i = 0; i < 8; i++)
4492 qemu_get_betls(f, &env->dr[i]);
4495 qemu_get_be32s(f, &env->a20_mask);
4497 qemu_get_be32s(f, &env->mxcsr);
4498 for(i = 0; i < CPU_NB_REGS; i++) {
4499 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
4500 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
4503 #ifdef TARGET_X86_64
4504 qemu_get_be64s(f, &env->efer);
4505 qemu_get_be64s(f, &env->star);
4506 qemu_get_be64s(f, &env->lstar);
4507 qemu_get_be64s(f, &env->cstar);
4508 qemu_get_be64s(f, &env->fmask);
4509 qemu_get_be64s(f, &env->kernelgsbase);
4512 /* XXX: compute hflags from scratch, except for CPL and IIF */
4513 env->hflags = hflags;
4518 #elif defined(TARGET_PPC)
4519 void cpu_save(QEMUFile *f, void *opaque)
4523 int cpu_load(QEMUFile *f, void *opaque, int version_id)
4528 #elif defined(TARGET_MIPS)
4529 void cpu_save(QEMUFile *f, void *opaque)
4533 int cpu_load(QEMUFile *f, void *opaque, int version_id)
4538 #elif defined(TARGET_SPARC)
4539 void cpu_save(QEMUFile *f, void *opaque)
4541 CPUState *env = opaque;
4545 for(i = 0; i < 8; i++)
4546 qemu_put_betls(f, &env->gregs[i]);
4547 for(i = 0; i < NWINDOWS * 16; i++)
4548 qemu_put_betls(f, &env->regbase[i]);
4551 for(i = 0; i < TARGET_FPREGS; i++) {
4557 qemu_put_be32(f, u.i);
4560 qemu_put_betls(f, &env->pc);
4561 qemu_put_betls(f, &env->npc);
4562 qemu_put_betls(f, &env->y);
4564 qemu_put_be32(f, tmp);
4565 qemu_put_betls(f, &env->fsr);
4566 qemu_put_betls(f, &env->tbr);
4567 #ifndef TARGET_SPARC64
4568 qemu_put_be32s(f, &env->wim);
4570 for(i = 0; i < 16; i++)
4571 qemu_put_be32s(f, &env->mmuregs[i]);
4575 int cpu_load(QEMUFile *f, void *opaque, int version_id)
4577 CPUState *env = opaque;
4581 for(i = 0; i < 8; i++)
4582 qemu_get_betls(f, &env->gregs[i]);
4583 for(i = 0; i < NWINDOWS * 16; i++)
4584 qemu_get_betls(f, &env->regbase[i]);
4587 for(i = 0; i < TARGET_FPREGS; i++) {
4592 u.i = qemu_get_be32(f);
4596 qemu_get_betls(f, &env->pc);
4597 qemu_get_betls(f, &env->npc);
4598 qemu_get_betls(f, &env->y);
4599 tmp = qemu_get_be32(f);
4600 env->cwp = 0; /* needed to ensure that the wrapping registers are
4601 correctly updated */
4603 qemu_get_betls(f, &env->fsr);
4604 qemu_get_betls(f, &env->tbr);
4605 #ifndef TARGET_SPARC64
4606 qemu_get_be32s(f, &env->wim);
4608 for(i = 0; i < 16; i++)
4609 qemu_get_be32s(f, &env->mmuregs[i]);
4615 #elif defined(TARGET_ARM)
4617 /* ??? Need to implement these. */
4618 void cpu_save(QEMUFile *f, void *opaque)
4622 int cpu_load(QEMUFile *f, void *opaque, int version_id)
4629 #warning No CPU save/restore functions
4633 /***********************************************************/
4634 /* ram save/restore */
4636 /* we just avoid storing empty pages */
4637 static void ram_put_page(QEMUFile *f, const uint8_t *buf, int len)
4642 for(i = 1; i < len; i++) {
4646 qemu_put_byte(f, 1);
4647 qemu_put_byte(f, v);
4650 qemu_put_byte(f, 0);
4651 qemu_put_buffer(f, buf, len);
4654 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
4658 v = qemu_get_byte(f);
4661 if (qemu_get_buffer(f, buf, len) != len)
4665 v = qemu_get_byte(f);
4666 memset(buf, v, len);
4674 static void ram_save(QEMUFile *f, void *opaque)
4677 qemu_put_be32(f, phys_ram_size);
4678 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
4679 ram_put_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
4683 static int ram_load(QEMUFile *f, void *opaque, int version_id)
4687 if (version_id != 1)
4689 if (qemu_get_be32(f) != phys_ram_size)
4691 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
4692 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
4699 /***********************************************************/
4700 /* machine registration */
4702 QEMUMachine *first_machine = NULL;
4704 int qemu_register_machine(QEMUMachine *m)
4707 pm = &first_machine;
4715 QEMUMachine *find_machine(const char *name)
4719 for(m = first_machine; m != NULL; m = m->next) {
4720 if (!strcmp(m->name, name))
4726 /***********************************************************/
4727 /* main execution loop */
4729 void gui_update(void *opaque)
4731 display_state.dpy_refresh(&display_state);
4732 qemu_mod_timer(gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
4735 struct vm_change_state_entry {
4736 VMChangeStateHandler *cb;
4738 LIST_ENTRY (vm_change_state_entry) entries;
4741 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
4743 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
4746 VMChangeStateEntry *e;
4748 e = qemu_mallocz(sizeof (*e));
4754 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
4758 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
4760 LIST_REMOVE (e, entries);
4764 static void vm_state_notify(int running)
4766 VMChangeStateEntry *e;
4768 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
4769 e->cb(e->opaque, running);
4773 /* XXX: support several handlers */
4774 static VMStopHandler *vm_stop_cb;
4775 static void *vm_stop_opaque;
4777 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
4780 vm_stop_opaque = opaque;
4784 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
4798 void vm_stop(int reason)
4801 cpu_disable_ticks();
4805 vm_stop_cb(vm_stop_opaque, reason);
4812 /* reset/shutdown handler */
4814 typedef struct QEMUResetEntry {
4815 QEMUResetHandler *func;
4817 struct QEMUResetEntry *next;
4820 static QEMUResetEntry *first_reset_entry;
4821 static int reset_requested;
4822 static int shutdown_requested;
4823 static int powerdown_requested;
4825 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
4827 QEMUResetEntry **pre, *re;
4829 pre = &first_reset_entry;
4830 while (*pre != NULL)
4831 pre = &(*pre)->next;
4832 re = qemu_mallocz(sizeof(QEMUResetEntry));
4834 re->opaque = opaque;
4839 void qemu_system_reset(void)
4843 /* reset all devices */
4844 for(re = first_reset_entry; re != NULL; re = re->next) {
4845 re->func(re->opaque);
4849 void qemu_system_reset_request(void)
4851 reset_requested = 1;
4853 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
4856 void qemu_system_shutdown_request(void)
4858 shutdown_requested = 1;
4860 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
4863 void qemu_system_powerdown_request(void)
4865 powerdown_requested = 1;
4867 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
4870 void main_loop_wait(int timeout)
4872 IOHandlerRecord *ioh, *ioh_next;
4873 fd_set rfds, wfds, xfds;
4879 /* XXX: need to suppress polling by better using win32 events */
4881 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
4882 ret |= pe->func(pe->opaque);
4885 if (ret == 0 && timeout > 0) {
4887 WaitObjects *w = &wait_objects;
4889 ret = WaitForMultipleObjects(w->num, w->events, FALSE, timeout);
4890 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
4891 if (w->func[ret - WAIT_OBJECT_0])
4892 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
4893 } else if (ret == WAIT_TIMEOUT) {
4895 err = GetLastError();
4896 fprintf(stderr, "Wait error %d %d\n", ret, err);
4900 /* poll any events */
4901 /* XXX: separate device handlers from system ones */
4906 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4908 (!ioh->fd_read_poll ||
4909 ioh->fd_read_poll(ioh->opaque) != 0)) {
4910 FD_SET(ioh->fd, &rfds);
4914 if (ioh->fd_write) {
4915 FD_SET(ioh->fd, &wfds);
4925 tv.tv_usec = timeout * 1000;
4927 #if defined(CONFIG_SLIRP)
4929 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
4932 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
4934 /* XXX: better handling of removal */
4935 for(ioh = first_io_handler; ioh != NULL; ioh = ioh_next) {
4936 ioh_next = ioh->next;
4937 if (FD_ISSET(ioh->fd, &rfds)) {
4938 ioh->fd_read(ioh->opaque);
4940 if (FD_ISSET(ioh->fd, &wfds)) {
4941 ioh->fd_write(ioh->opaque);
4945 #if defined(CONFIG_SLIRP)
4952 slirp_select_poll(&rfds, &wfds, &xfds);
4960 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
4961 qemu_get_clock(vm_clock));
4962 /* run dma transfers, if any */
4966 /* real time timers */
4967 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
4968 qemu_get_clock(rt_clock));
4971 static CPUState *cur_cpu;
4976 #ifdef CONFIG_PROFILER
4981 cur_cpu = first_cpu;
4988 env = env->next_cpu;
4991 #ifdef CONFIG_PROFILER
4992 ti = profile_getclock();
4994 ret = cpu_exec(env);
4995 #ifdef CONFIG_PROFILER
4996 qemu_time += profile_getclock() - ti;
4998 if (ret != EXCP_HALTED)
5000 /* all CPUs are halted ? */
5001 if (env == cur_cpu) {
5008 if (shutdown_requested) {
5009 ret = EXCP_INTERRUPT;
5012 if (reset_requested) {
5013 reset_requested = 0;
5014 qemu_system_reset();
5015 ret = EXCP_INTERRUPT;
5017 if (powerdown_requested) {
5018 powerdown_requested = 0;
5019 qemu_system_powerdown();
5020 ret = EXCP_INTERRUPT;
5022 if (ret == EXCP_DEBUG) {
5023 vm_stop(EXCP_DEBUG);
5025 /* if hlt instruction, we wait until the next IRQ */
5026 /* XXX: use timeout computed from timers */
5027 if (ret == EXCP_HLT)
5034 #ifdef CONFIG_PROFILER
5035 ti = profile_getclock();
5037 main_loop_wait(timeout);
5038 #ifdef CONFIG_PROFILER
5039 dev_time += profile_getclock() - ti;
5042 cpu_disable_ticks();
5048 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2005 Fabrice Bellard\n"
5049 "usage: %s [options] [disk_image]\n"
5051 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
5053 "Standard options:\n"
5054 "-M machine select emulated machine (-M ? for list)\n"
5055 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
5056 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
5057 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
5058 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
5059 "-boot [a|c|d] boot on floppy (a), hard disk (c) or CD-ROM (d)\n"
5060 "-snapshot write to temporary files instead of disk image files\n"
5062 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
5064 "-m megs set virtual RAM size to megs MB [default=%d]\n"
5065 "-smp n set the number of CPUs to 'n' [default=1]\n"
5066 "-nographic disable graphical output and redirect serial I/Os to console\n"
5068 "-k language use keyboard layout (for example \"fr\" for French)\n"
5071 "-audio-help print list of audio drivers and their options\n"
5072 "-soundhw c1,... enable audio support\n"
5073 " and only specified sound cards (comma separated list)\n"
5074 " use -soundhw ? to get the list of supported cards\n"
5075 " use -soundhw all to enable all of them\n"
5077 "-localtime set the real time clock to local time [default=utc]\n"
5078 "-full-screen start in full screen\n"
5080 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
5082 "-usb enable the USB driver (will be the default soon)\n"
5083 "-usbdevice name add the host or guest USB device 'name'\n"
5084 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
5085 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
5088 "Network options:\n"
5089 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
5090 " create a new Network Interface Card and connect it to VLAN 'n'\n"
5092 "-net user[,vlan=n][,hostname=host]\n"
5093 " connect the user mode network stack to VLAN 'n' and send\n"
5094 " hostname 'host' to DHCP clients\n"
5097 "-net tap[,vlan=n],ifname=name\n"
5098 " connect the host TAP network interface to VLAN 'n'\n"
5100 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file]\n"
5101 " connect the host TAP network interface to VLAN 'n' and use\n"
5102 " the network script 'file' (default=%s);\n"
5103 " use 'fd=h' to connect to an already opened TAP interface\n"
5105 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
5106 " connect the vlan 'n' to another VLAN using a socket connection\n"
5107 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
5108 " connect the vlan 'n' to multicast maddr and port\n"
5109 "-net none use it alone to have zero network devices; if no -net option\n"
5110 " is provided, the default is '-net nic -net user'\n"
5113 "-tftp prefix allow tftp access to files starting with prefix [-net user]\n"
5115 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
5117 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
5118 " redirect TCP or UDP connections from host to guest [-net user]\n"
5121 "Linux boot specific:\n"
5122 "-kernel bzImage use 'bzImage' as kernel image\n"
5123 "-append cmdline use 'cmdline' as kernel command line\n"
5124 "-initrd file use 'file' as initial ram disk\n"
5126 "Debug/Expert options:\n"
5127 "-monitor dev redirect the monitor to char device 'dev'\n"
5128 "-serial dev redirect the serial port to char device 'dev'\n"
5129 "-parallel dev redirect the parallel port to char device 'dev'\n"
5130 "-pidfile file Write PID to 'file'\n"
5131 "-S freeze CPU at startup (use 'c' to start execution)\n"
5132 "-s wait gdb connection to port %d\n"
5133 "-p port change gdb connection port\n"
5134 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
5135 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
5136 " translation (t=none or lba) (usually qemu can guess them)\n"
5137 "-L path set the directory for the BIOS and VGA BIOS\n"
5139 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
5140 "-no-kqemu disable KQEMU kernel module usage\n"
5142 #ifdef USE_CODE_COPY
5143 "-no-code-copy disable code copy acceleration\n"
5146 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
5147 " (default is CL-GD5446 PCI VGA)\n"
5148 "-no-acpi disable ACPI\n"
5150 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
5151 "-vnc display start a VNC server on display\n"
5153 "During emulation, the following keys are useful:\n"
5154 "ctrl-alt-f toggle full screen\n"
5155 "ctrl-alt-n switch to virtual console 'n'\n"
5156 "ctrl-alt toggle mouse and keyboard grab\n"
5158 "When using -nographic, press 'ctrl-a h' to get some help.\n"
5163 DEFAULT_NETWORK_SCRIPT,
5165 DEFAULT_GDBSTUB_PORT,
5170 #define HAS_ARG 0x0001
5184 QEMU_OPTION_snapshot,
5186 QEMU_OPTION_no_fd_bootchk,
5189 QEMU_OPTION_nographic,
5191 QEMU_OPTION_audio_help,
5192 QEMU_OPTION_soundhw,
5210 QEMU_OPTION_no_code_copy,
5212 QEMU_OPTION_localtime,
5213 QEMU_OPTION_cirrusvga,
5215 QEMU_OPTION_std_vga,
5216 QEMU_OPTION_monitor,
5218 QEMU_OPTION_parallel,
5220 QEMU_OPTION_full_screen,
5221 QEMU_OPTION_pidfile,
5222 QEMU_OPTION_no_kqemu,
5223 QEMU_OPTION_kernel_kqemu,
5224 QEMU_OPTION_win2k_hack,
5226 QEMU_OPTION_usbdevice,
5229 QEMU_OPTION_no_acpi,
5232 typedef struct QEMUOption {
5238 const QEMUOption qemu_options[] = {
5239 { "h", 0, QEMU_OPTION_h },
5241 { "M", HAS_ARG, QEMU_OPTION_M },
5242 { "fda", HAS_ARG, QEMU_OPTION_fda },
5243 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
5244 { "hda", HAS_ARG, QEMU_OPTION_hda },
5245 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
5246 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
5247 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
5248 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
5249 { "boot", HAS_ARG, QEMU_OPTION_boot },
5250 { "snapshot", 0, QEMU_OPTION_snapshot },
5252 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
5254 { "m", HAS_ARG, QEMU_OPTION_m },
5255 { "nographic", 0, QEMU_OPTION_nographic },
5256 { "k", HAS_ARG, QEMU_OPTION_k },
5258 { "audio-help", 0, QEMU_OPTION_audio_help },
5259 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
5262 { "net", HAS_ARG, QEMU_OPTION_net},
5264 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
5266 { "smb", HAS_ARG, QEMU_OPTION_smb },
5268 { "redir", HAS_ARG, QEMU_OPTION_redir },
5271 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
5272 { "append", HAS_ARG, QEMU_OPTION_append },
5273 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
5275 { "S", 0, QEMU_OPTION_S },
5276 { "s", 0, QEMU_OPTION_s },
5277 { "p", HAS_ARG, QEMU_OPTION_p },
5278 { "d", HAS_ARG, QEMU_OPTION_d },
5279 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
5280 { "L", HAS_ARG, QEMU_OPTION_L },
5281 { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
5283 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
5284 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
5286 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
5287 { "g", 1, QEMU_OPTION_g },
5289 { "localtime", 0, QEMU_OPTION_localtime },
5290 { "std-vga", 0, QEMU_OPTION_std_vga },
5291 { "monitor", 1, QEMU_OPTION_monitor },
5292 { "serial", 1, QEMU_OPTION_serial },
5293 { "parallel", 1, QEMU_OPTION_parallel },
5294 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
5295 { "full-screen", 0, QEMU_OPTION_full_screen },
5296 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
5297 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
5298 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
5299 { "smp", HAS_ARG, QEMU_OPTION_smp },
5300 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
5302 /* temporary options */
5303 { "usb", 0, QEMU_OPTION_usb },
5304 { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
5305 { "no-acpi", 0, QEMU_OPTION_no_acpi },
5309 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
5311 /* this stack is only used during signal handling */
5312 #define SIGNAL_STACK_SIZE 32768
5314 static uint8_t *signal_stack;
5318 /* password input */
5320 static BlockDriverState *get_bdrv(int index)
5322 BlockDriverState *bs;
5325 bs = bs_table[index];
5326 } else if (index < 6) {
5327 bs = fd_table[index - 4];
5334 static void read_passwords(void)
5336 BlockDriverState *bs;
5340 for(i = 0; i < 6; i++) {
5342 if (bs && bdrv_is_encrypted(bs)) {
5343 term_printf("%s is encrypted.\n", bdrv_get_device_name(bs));
5344 for(j = 0; j < 3; j++) {
5345 monitor_readline("Password: ",
5346 1, password, sizeof(password));
5347 if (bdrv_set_key(bs, password) == 0)
5349 term_printf("invalid password\n");
5355 /* XXX: currently we cannot use simultaneously different CPUs */
5356 void register_machines(void)
5358 #if defined(TARGET_I386)
5359 qemu_register_machine(&pc_machine);
5360 qemu_register_machine(&isapc_machine);
5361 #elif defined(TARGET_PPC)
5362 qemu_register_machine(&heathrow_machine);
5363 qemu_register_machine(&core99_machine);
5364 qemu_register_machine(&prep_machine);
5365 #elif defined(TARGET_MIPS)
5366 qemu_register_machine(&mips_machine);
5367 #elif defined(TARGET_SPARC)
5368 #ifdef TARGET_SPARC64
5369 qemu_register_machine(&sun4u_machine);
5371 qemu_register_machine(&sun4m_machine);
5373 #elif defined(TARGET_ARM)
5374 qemu_register_machine(&integratorcp926_machine);
5375 qemu_register_machine(&integratorcp1026_machine);
5376 qemu_register_machine(&versatilepb_machine);
5377 qemu_register_machine(&versatileab_machine);
5378 #elif defined(TARGET_SH4)
5379 qemu_register_machine(&shix_machine);
5381 #error unsupported CPU
5386 struct soundhw soundhw[] = {
5393 { .init_isa = pcspk_audio_init }
5398 "Creative Sound Blaster 16",
5401 { .init_isa = SB16_init }
5408 "Yamaha YMF262 (OPL3)",
5410 "Yamaha YM3812 (OPL2)",
5414 { .init_isa = Adlib_init }
5421 "Gravis Ultrasound GF1",
5424 { .init_isa = GUS_init }
5430 "ENSONIQ AudioPCI ES1370",
5433 { .init_pci = es1370_init }
5436 { NULL, NULL, 0, 0, { NULL } }
5439 static void select_soundhw (const char *optarg)
5443 if (*optarg == '?') {
5446 printf ("Valid sound card names (comma separated):\n");
5447 for (c = soundhw; c->name; ++c) {
5448 printf ("%-11s %s\n", c->name, c->descr);
5450 printf ("\n-soundhw all will enable all of the above\n");
5451 exit (*optarg != '?');
5459 if (!strcmp (optarg, "all")) {
5460 for (c = soundhw; c->name; ++c) {
5468 e = strchr (p, ',');
5469 l = !e ? strlen (p) : (size_t) (e - p);
5471 for (c = soundhw; c->name; ++c) {
5472 if (!strncmp (c->name, p, l)) {
5481 "Unknown sound card name (too big to show)\n");
5484 fprintf (stderr, "Unknown sound card name `%.*s'\n",
5489 p += l + (e != NULL);
5493 goto show_valid_cards;
5499 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
5501 exit(STATUS_CONTROL_C_EXIT);
5506 #define MAX_NET_CLIENTS 32
5508 int main(int argc, char **argv)
5510 #ifdef CONFIG_GDBSTUB
5511 int use_gdbstub, gdbstub_port;
5514 int snapshot, linux_boot;
5515 const char *initrd_filename;
5516 const char *hd_filename[MAX_DISKS], *fd_filename[MAX_FD];
5517 const char *kernel_filename, *kernel_cmdline;
5518 DisplayState *ds = &display_state;
5519 int cyls, heads, secs, translation;
5520 int start_emulation = 1;
5521 char net_clients[MAX_NET_CLIENTS][256];
5524 const char *r, *optarg;
5525 CharDriverState *monitor_hd;
5526 char monitor_device[128];
5527 char serial_devices[MAX_SERIAL_PORTS][128];
5528 int serial_device_index;
5529 char parallel_devices[MAX_PARALLEL_PORTS][128];
5530 int parallel_device_index;
5531 const char *loadvm = NULL;
5532 QEMUMachine *machine;
5533 char usb_devices[MAX_USB_CMDLINE][128];
5534 int usb_devices_index;
5536 LIST_INIT (&vm_change_state_head);
5539 struct sigaction act;
5540 sigfillset(&act.sa_mask);
5542 act.sa_handler = SIG_IGN;
5543 sigaction(SIGPIPE, &act, NULL);
5546 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
5550 register_machines();
5551 machine = first_machine;
5552 initrd_filename = NULL;
5553 for(i = 0; i < MAX_FD; i++)
5554 fd_filename[i] = NULL;
5555 for(i = 0; i < MAX_DISKS; i++)
5556 hd_filename[i] = NULL;
5557 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5558 vga_ram_size = VGA_RAM_SIZE;
5559 bios_size = BIOS_SIZE;
5560 #ifdef CONFIG_GDBSTUB
5562 gdbstub_port = DEFAULT_GDBSTUB_PORT;
5566 kernel_filename = NULL;
5567 kernel_cmdline = "";
5573 cyls = heads = secs = 0;
5574 translation = BIOS_ATA_TRANSLATION_AUTO;
5575 pstrcpy(monitor_device, sizeof(monitor_device), "vc");
5577 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
5578 for(i = 1; i < MAX_SERIAL_PORTS; i++)
5579 serial_devices[i][0] = '\0';
5580 serial_device_index = 0;
5582 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
5583 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
5584 parallel_devices[i][0] = '\0';
5585 parallel_device_index = 0;
5587 usb_devices_index = 0;
5592 /* default mac address of the first network interface */
5600 hd_filename[0] = argv[optind++];
5602 const QEMUOption *popt;
5605 popt = qemu_options;
5608 fprintf(stderr, "%s: invalid option -- '%s'\n",
5612 if (!strcmp(popt->name, r + 1))
5616 if (popt->flags & HAS_ARG) {
5617 if (optind >= argc) {
5618 fprintf(stderr, "%s: option '%s' requires an argument\n",
5622 optarg = argv[optind++];
5627 switch(popt->index) {
5629 machine = find_machine(optarg);
5632 printf("Supported machines are:\n");
5633 for(m = first_machine; m != NULL; m = m->next) {
5634 printf("%-10s %s%s\n",
5636 m == first_machine ? " (default)" : "");
5641 case QEMU_OPTION_initrd:
5642 initrd_filename = optarg;
5644 case QEMU_OPTION_hda:
5645 case QEMU_OPTION_hdb:
5646 case QEMU_OPTION_hdc:
5647 case QEMU_OPTION_hdd:
5650 hd_index = popt->index - QEMU_OPTION_hda;
5651 hd_filename[hd_index] = optarg;
5652 if (hd_index == cdrom_index)
5656 case QEMU_OPTION_snapshot:
5659 case QEMU_OPTION_hdachs:
5663 cyls = strtol(p, (char **)&p, 0);
5664 if (cyls < 1 || cyls > 16383)
5669 heads = strtol(p, (char **)&p, 0);
5670 if (heads < 1 || heads > 16)
5675 secs = strtol(p, (char **)&p, 0);
5676 if (secs < 1 || secs > 63)
5680 if (!strcmp(p, "none"))
5681 translation = BIOS_ATA_TRANSLATION_NONE;
5682 else if (!strcmp(p, "lba"))
5683 translation = BIOS_ATA_TRANSLATION_LBA;
5684 else if (!strcmp(p, "auto"))
5685 translation = BIOS_ATA_TRANSLATION_AUTO;
5688 } else if (*p != '\0') {
5690 fprintf(stderr, "qemu: invalid physical CHS format\n");
5695 case QEMU_OPTION_nographic:
5696 pstrcpy(monitor_device, sizeof(monitor_device), "stdio");
5697 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "stdio");
5700 case QEMU_OPTION_kernel:
5701 kernel_filename = optarg;
5703 case QEMU_OPTION_append:
5704 kernel_cmdline = optarg;
5706 case QEMU_OPTION_cdrom:
5707 if (cdrom_index >= 0) {
5708 hd_filename[cdrom_index] = optarg;
5711 case QEMU_OPTION_boot:
5712 boot_device = optarg[0];
5713 if (boot_device != 'a' &&
5716 boot_device != 'n' &&
5718 boot_device != 'c' && boot_device != 'd') {
5719 fprintf(stderr, "qemu: invalid boot device '%c'\n", boot_device);
5723 case QEMU_OPTION_fda:
5724 fd_filename[0] = optarg;
5726 case QEMU_OPTION_fdb:
5727 fd_filename[1] = optarg;
5730 case QEMU_OPTION_no_fd_bootchk:
5734 case QEMU_OPTION_no_code_copy:
5735 code_copy_enabled = 0;
5737 case QEMU_OPTION_net:
5738 if (nb_net_clients >= MAX_NET_CLIENTS) {
5739 fprintf(stderr, "qemu: too many network clients\n");
5742 pstrcpy(net_clients[nb_net_clients],
5743 sizeof(net_clients[0]),
5748 case QEMU_OPTION_tftp:
5749 tftp_prefix = optarg;
5752 case QEMU_OPTION_smb:
5753 net_slirp_smb(optarg);
5756 case QEMU_OPTION_redir:
5757 net_slirp_redir(optarg);
5761 case QEMU_OPTION_audio_help:
5765 case QEMU_OPTION_soundhw:
5766 select_soundhw (optarg);
5773 ram_size = atoi(optarg) * 1024 * 1024;
5776 if (ram_size > PHYS_RAM_MAX_SIZE) {
5777 fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
5778 PHYS_RAM_MAX_SIZE / (1024 * 1024));
5787 mask = cpu_str_to_log_mask(optarg);
5789 printf("Log items (comma separated):\n");
5790 for(item = cpu_log_items; item->mask != 0; item++) {
5791 printf("%-10s %s\n", item->name, item->help);
5798 #ifdef CONFIG_GDBSTUB
5803 gdbstub_port = atoi(optarg);
5810 start_emulation = 0;
5813 keyboard_layout = optarg;
5815 case QEMU_OPTION_localtime:
5818 case QEMU_OPTION_cirrusvga:
5819 cirrus_vga_enabled = 1;
5821 case QEMU_OPTION_std_vga:
5822 cirrus_vga_enabled = 0;
5829 w = strtol(p, (char **)&p, 10);
5832 fprintf(stderr, "qemu: invalid resolution or depth\n");
5838 h = strtol(p, (char **)&p, 10);
5843 depth = strtol(p, (char **)&p, 10);
5844 if (depth != 8 && depth != 15 && depth != 16 &&
5845 depth != 24 && depth != 32)
5847 } else if (*p == '\0') {
5848 depth = graphic_depth;
5855 graphic_depth = depth;
5858 case QEMU_OPTION_monitor:
5859 pstrcpy(monitor_device, sizeof(monitor_device), optarg);
5861 case QEMU_OPTION_serial:
5862 if (serial_device_index >= MAX_SERIAL_PORTS) {
5863 fprintf(stderr, "qemu: too many serial ports\n");
5866 pstrcpy(serial_devices[serial_device_index],
5867 sizeof(serial_devices[0]), optarg);
5868 serial_device_index++;
5870 case QEMU_OPTION_parallel:
5871 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
5872 fprintf(stderr, "qemu: too many parallel ports\n");
5875 pstrcpy(parallel_devices[parallel_device_index],
5876 sizeof(parallel_devices[0]), optarg);
5877 parallel_device_index++;
5879 case QEMU_OPTION_loadvm:
5882 case QEMU_OPTION_full_screen:
5885 case QEMU_OPTION_pidfile:
5886 create_pidfile(optarg);
5889 case QEMU_OPTION_win2k_hack:
5890 win2k_install_hack = 1;
5894 case QEMU_OPTION_no_kqemu:
5897 case QEMU_OPTION_kernel_kqemu:
5901 case QEMU_OPTION_usb:
5904 case QEMU_OPTION_usbdevice:
5906 if (usb_devices_index >= MAX_USB_CMDLINE) {
5907 fprintf(stderr, "Too many USB devices\n");
5910 pstrcpy(usb_devices[usb_devices_index],
5911 sizeof(usb_devices[usb_devices_index]),
5913 usb_devices_index++;
5915 case QEMU_OPTION_smp:
5916 smp_cpus = atoi(optarg);
5917 if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
5918 fprintf(stderr, "Invalid number of CPUs\n");
5922 case QEMU_OPTION_vnc:
5923 vnc_display = atoi(optarg);
5924 if (vnc_display < 0) {
5925 fprintf(stderr, "Invalid VNC display\n");
5929 case QEMU_OPTION_no_acpi:
5940 linux_boot = (kernel_filename != NULL);
5943 hd_filename[0] == '\0' &&
5944 (cdrom_index >= 0 && hd_filename[cdrom_index] == '\0') &&
5945 fd_filename[0] == '\0')
5948 /* boot to cd by default if no hard disk */
5949 if (hd_filename[0] == '\0' && boot_device == 'c') {
5950 if (fd_filename[0] != '\0')
5956 setvbuf(stdout, NULL, _IOLBF, 0);
5962 /* init network clients */
5963 if (nb_net_clients == 0) {
5964 /* if no clients, we use a default config */
5965 pstrcpy(net_clients[0], sizeof(net_clients[0]),
5967 pstrcpy(net_clients[1], sizeof(net_clients[0]),
5972 for(i = 0;i < nb_net_clients; i++) {
5973 if (net_client_init(net_clients[i]) < 0)
5977 /* init the memory */
5978 phys_ram_size = ram_size + vga_ram_size + bios_size;
5980 phys_ram_base = qemu_vmalloc(phys_ram_size);
5981 if (!phys_ram_base) {
5982 fprintf(stderr, "Could not allocate physical memory\n");
5986 /* we always create the cdrom drive, even if no disk is there */
5988 if (cdrom_index >= 0) {
5989 bs_table[cdrom_index] = bdrv_new("cdrom");
5990 bdrv_set_type_hint(bs_table[cdrom_index], BDRV_TYPE_CDROM);
5993 /* open the virtual block devices */
5994 for(i = 0; i < MAX_DISKS; i++) {
5995 if (hd_filename[i]) {
5998 snprintf(buf, sizeof(buf), "hd%c", i + 'a');
5999 bs_table[i] = bdrv_new(buf);
6001 if (bdrv_open(bs_table[i], hd_filename[i], snapshot) < 0) {
6002 fprintf(stderr, "qemu: could not open hard disk image '%s'\n",
6006 if (i == 0 && cyls != 0) {
6007 bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
6008 bdrv_set_translation_hint(bs_table[i], translation);
6013 /* we always create at least one floppy disk */
6014 fd_table[0] = bdrv_new("fda");
6015 bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
6017 for(i = 0; i < MAX_FD; i++) {
6018 if (fd_filename[i]) {
6021 snprintf(buf, sizeof(buf), "fd%c", i + 'a');
6022 fd_table[i] = bdrv_new(buf);
6023 bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
6025 if (fd_filename[i] != '\0') {
6026 if (bdrv_open(fd_table[i], fd_filename[i], snapshot) < 0) {
6027 fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
6035 register_savevm("timer", 0, 1, timer_save, timer_load, NULL);
6036 register_savevm("ram", 0, 1, ram_save, ram_load, NULL);
6039 cpu_calibrate_ticks();
6043 dumb_display_init(ds);
6044 } else if (vnc_display != -1) {
6045 vnc_display_init(ds, vnc_display);
6047 #if defined(CONFIG_SDL)
6048 sdl_display_init(ds, full_screen);
6049 #elif defined(CONFIG_COCOA)
6050 cocoa_display_init(ds, full_screen);
6052 dumb_display_init(ds);
6056 monitor_hd = qemu_chr_open(monitor_device);
6058 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
6061 monitor_init(monitor_hd, !nographic);
6063 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
6064 if (serial_devices[i][0] != '\0') {
6065 serial_hds[i] = qemu_chr_open(serial_devices[i]);
6066 if (!serial_hds[i]) {
6067 fprintf(stderr, "qemu: could not open serial device '%s'\n",
6071 if (!strcmp(serial_devices[i], "vc"))
6072 qemu_chr_printf(serial_hds[i], "serial%d console\n", i);
6076 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
6077 if (parallel_devices[i][0] != '\0') {
6078 parallel_hds[i] = qemu_chr_open(parallel_devices[i]);
6079 if (!parallel_hds[i]) {
6080 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
6081 parallel_devices[i]);
6084 if (!strcmp(parallel_devices[i], "vc"))
6085 qemu_chr_printf(parallel_hds[i], "parallel%d console\n", i);
6089 machine->init(ram_size, vga_ram_size, boot_device,
6090 ds, fd_filename, snapshot,
6091 kernel_filename, kernel_cmdline, initrd_filename);
6093 /* init USB devices */
6095 for(i = 0; i < usb_devices_index; i++) {
6096 if (usb_device_add(usb_devices[i]) < 0) {
6097 fprintf(stderr, "Warning: could not add USB device %s\n",
6103 gui_timer = qemu_new_timer(rt_clock, gui_update, NULL);
6104 qemu_mod_timer(gui_timer, qemu_get_clock(rt_clock));
6106 #ifdef CONFIG_GDBSTUB
6108 if (gdbserver_start(gdbstub_port) < 0) {
6109 fprintf(stderr, "Could not open gdbserver socket on port %d\n",
6113 printf("Waiting gdb connection on port %d\n", gdbstub_port);
6118 qemu_loadvm(loadvm);
6121 /* XXX: simplify init */
6123 if (start_emulation) {