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 #if !defined(CONFIG_SOFTMMU)
96 #define PHYS_RAM_MAX_SIZE (256 * 1024 * 1024)
98 #define PHYS_RAM_MAX_SIZE (2047 * 1024 * 1024)
102 #define DEFAULT_RAM_SIZE 144
104 #define DEFAULT_RAM_SIZE 128
107 #define GUI_REFRESH_INTERVAL 30
109 /* Max number of USB devices that can be specified on the commandline. */
110 #define MAX_USB_CMDLINE 8
112 /* XXX: use a two level table to limit memory usage */
113 #define MAX_IOPORTS 65536
115 const char *bios_dir = CONFIG_QEMU_SHAREDIR;
116 char phys_ram_file[1024];
117 void *ioport_opaque[MAX_IOPORTS];
118 IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
119 IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
120 BlockDriverState *bs_table[MAX_DISKS], *fd_table[MAX_FD];
123 static DisplayState display_state;
125 const char* keyboard_layout = NULL;
126 int64_t ticks_per_sec;
127 int boot_device = 'c';
129 int pit_min_timer_count = 0;
131 NICInfo nd_table[MAX_NICS];
132 QEMUTimer *gui_timer;
135 int cirrus_vga_enabled = 1;
137 int graphic_width = 1024;
138 int graphic_height = 768;
140 int graphic_width = 800;
141 int graphic_height = 600;
143 int graphic_depth = 15;
145 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
146 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
148 int win2k_install_hack = 0;
151 static VLANState *first_vlan;
153 int vnc_display = -1;
154 #if defined(TARGET_SPARC)
156 #elif defined(TARGET_I386)
161 int acpi_enabled = 1;
164 /***********************************************************/
165 /* x86 ISA bus support */
167 target_phys_addr_t isa_mem_base = 0;
170 uint32_t default_ioport_readb(void *opaque, uint32_t address)
172 #ifdef DEBUG_UNUSED_IOPORT
173 fprintf(stderr, "inb: port=0x%04x\n", address);
178 void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
180 #ifdef DEBUG_UNUSED_IOPORT
181 fprintf(stderr, "outb: port=0x%04x data=0x%02x\n", address, data);
185 /* default is to make two byte accesses */
186 uint32_t default_ioport_readw(void *opaque, uint32_t address)
189 data = ioport_read_table[0][address](ioport_opaque[address], address);
190 address = (address + 1) & (MAX_IOPORTS - 1);
191 data |= ioport_read_table[0][address](ioport_opaque[address], address) << 8;
195 void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
197 ioport_write_table[0][address](ioport_opaque[address], address, data & 0xff);
198 address = (address + 1) & (MAX_IOPORTS - 1);
199 ioport_write_table[0][address](ioport_opaque[address], address, (data >> 8) & 0xff);
202 uint32_t default_ioport_readl(void *opaque, uint32_t address)
204 #ifdef DEBUG_UNUSED_IOPORT
205 fprintf(stderr, "inl: port=0x%04x\n", address);
210 void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
212 #ifdef DEBUG_UNUSED_IOPORT
213 fprintf(stderr, "outl: port=0x%04x data=0x%02x\n", address, data);
217 void init_ioports(void)
221 for(i = 0; i < MAX_IOPORTS; i++) {
222 ioport_read_table[0][i] = default_ioport_readb;
223 ioport_write_table[0][i] = default_ioport_writeb;
224 ioport_read_table[1][i] = default_ioport_readw;
225 ioport_write_table[1][i] = default_ioport_writew;
226 ioport_read_table[2][i] = default_ioport_readl;
227 ioport_write_table[2][i] = default_ioport_writel;
231 /* size is the word size in byte */
232 int register_ioport_read(int start, int length, int size,
233 IOPortReadFunc *func, void *opaque)
239 } else if (size == 2) {
241 } else if (size == 4) {
244 hw_error("register_ioport_read: invalid size");
247 for(i = start; i < start + length; i += size) {
248 ioport_read_table[bsize][i] = func;
249 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
250 hw_error("register_ioport_read: invalid opaque");
251 ioport_opaque[i] = opaque;
256 /* size is the word size in byte */
257 int register_ioport_write(int start, int length, int size,
258 IOPortWriteFunc *func, void *opaque)
264 } else if (size == 2) {
266 } else if (size == 4) {
269 hw_error("register_ioport_write: invalid size");
272 for(i = start; i < start + length; i += size) {
273 ioport_write_table[bsize][i] = func;
274 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
275 hw_error("register_ioport_read: invalid opaque");
276 ioport_opaque[i] = opaque;
281 void isa_unassign_ioport(int start, int length)
285 for(i = start; i < start + length; i++) {
286 ioport_read_table[0][i] = default_ioport_readb;
287 ioport_read_table[1][i] = default_ioport_readw;
288 ioport_read_table[2][i] = default_ioport_readl;
290 ioport_write_table[0][i] = default_ioport_writeb;
291 ioport_write_table[1][i] = default_ioport_writew;
292 ioport_write_table[2][i] = default_ioport_writel;
296 /***********************************************************/
298 void pstrcpy(char *buf, int buf_size, const char *str)
308 if (c == 0 || q >= buf + buf_size - 1)
315 /* strcat and truncate. */
316 char *pstrcat(char *buf, int buf_size, const char *s)
321 pstrcpy(buf + len, buf_size - len, s);
325 int strstart(const char *str, const char *val, const char **ptr)
341 void cpu_outb(CPUState *env, int addr, int val)
344 if (loglevel & CPU_LOG_IOPORT)
345 fprintf(logfile, "outb: %04x %02x\n", addr, val);
347 ioport_write_table[0][addr](ioport_opaque[addr], addr, val);
350 env->last_io_time = cpu_get_time_fast();
354 void cpu_outw(CPUState *env, int addr, int val)
357 if (loglevel & CPU_LOG_IOPORT)
358 fprintf(logfile, "outw: %04x %04x\n", addr, val);
360 ioport_write_table[1][addr](ioport_opaque[addr], addr, val);
363 env->last_io_time = cpu_get_time_fast();
367 void cpu_outl(CPUState *env, int addr, int val)
370 if (loglevel & CPU_LOG_IOPORT)
371 fprintf(logfile, "outl: %04x %08x\n", addr, val);
373 ioport_write_table[2][addr](ioport_opaque[addr], addr, val);
376 env->last_io_time = cpu_get_time_fast();
380 int cpu_inb(CPUState *env, int addr)
383 val = ioport_read_table[0][addr](ioport_opaque[addr], addr);
385 if (loglevel & CPU_LOG_IOPORT)
386 fprintf(logfile, "inb : %04x %02x\n", addr, val);
390 env->last_io_time = cpu_get_time_fast();
395 int cpu_inw(CPUState *env, int addr)
398 val = ioport_read_table[1][addr](ioport_opaque[addr], addr);
400 if (loglevel & CPU_LOG_IOPORT)
401 fprintf(logfile, "inw : %04x %04x\n", addr, val);
405 env->last_io_time = cpu_get_time_fast();
410 int cpu_inl(CPUState *env, int addr)
413 val = ioport_read_table[2][addr](ioport_opaque[addr], addr);
415 if (loglevel & CPU_LOG_IOPORT)
416 fprintf(logfile, "inl : %04x %08x\n", addr, val);
420 env->last_io_time = cpu_get_time_fast();
425 /***********************************************************/
426 void hw_error(const char *fmt, ...)
432 fprintf(stderr, "qemu: hardware error: ");
433 vfprintf(stderr, fmt, ap);
434 fprintf(stderr, "\n");
435 for(env = first_cpu; env != NULL; env = env->next_cpu) {
436 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
438 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
440 cpu_dump_state(env, stderr, fprintf, 0);
447 /***********************************************************/
450 static QEMUPutKBDEvent *qemu_put_kbd_event;
451 static void *qemu_put_kbd_event_opaque;
452 static QEMUPutMouseEvent *qemu_put_mouse_event;
453 static void *qemu_put_mouse_event_opaque;
454 static int qemu_put_mouse_event_absolute;
456 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
458 qemu_put_kbd_event_opaque = opaque;
459 qemu_put_kbd_event = func;
462 void qemu_add_mouse_event_handler(QEMUPutMouseEvent *func, void *opaque, int absolute)
464 qemu_put_mouse_event_opaque = opaque;
465 qemu_put_mouse_event = func;
466 qemu_put_mouse_event_absolute = absolute;
469 void kbd_put_keycode(int keycode)
471 if (qemu_put_kbd_event) {
472 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
476 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
478 if (qemu_put_mouse_event) {
479 qemu_put_mouse_event(qemu_put_mouse_event_opaque,
480 dx, dy, dz, buttons_state);
484 int kbd_mouse_is_absolute(void)
486 return qemu_put_mouse_event_absolute;
489 /***********************************************************/
492 #if defined(__powerpc__)
494 static inline uint32_t get_tbl(void)
497 asm volatile("mftb %0" : "=r" (tbl));
501 static inline uint32_t get_tbu(void)
504 asm volatile("mftbu %0" : "=r" (tbl));
508 int64_t cpu_get_real_ticks(void)
511 /* NOTE: we test if wrapping has occurred */
517 return ((int64_t)h << 32) | l;
520 #elif defined(__i386__)
522 int64_t cpu_get_real_ticks(void)
526 QueryPerformanceCounter(&ti);
530 asm volatile ("rdtsc" : "=A" (val));
535 #elif defined(__x86_64__)
537 int64_t cpu_get_real_ticks(void)
541 asm volatile("rdtsc" : "=a" (low), "=d" (high));
548 #elif defined(__ia64)
550 int64_t cpu_get_real_ticks(void)
553 asm volatile ("mov %0 = ar.itc" : "=r"(val) :: "memory");
557 #elif defined(__s390__)
559 int64_t cpu_get_real_ticks(void)
562 asm volatile("stck 0(%1)" : "=m" (val) : "a" (&val) : "cc");
567 #error unsupported CPU
570 static int64_t cpu_ticks_prev;
571 static int64_t cpu_ticks_offset;
572 static int cpu_ticks_enabled;
574 static inline int64_t cpu_get_ticks(void)
576 if (!cpu_ticks_enabled) {
577 return cpu_ticks_offset;
580 ticks = cpu_get_real_ticks();
581 if (cpu_ticks_prev > ticks) {
582 /* Note: non increasing ticks may happen if the host uses
584 cpu_ticks_offset += cpu_ticks_prev - ticks;
586 cpu_ticks_prev = ticks;
587 return ticks + cpu_ticks_offset;
591 /* enable cpu_get_ticks() */
592 void cpu_enable_ticks(void)
594 if (!cpu_ticks_enabled) {
595 cpu_ticks_offset -= cpu_get_real_ticks();
596 cpu_ticks_enabled = 1;
600 /* disable cpu_get_ticks() : the clock is stopped. You must not call
601 cpu_get_ticks() after that. */
602 void cpu_disable_ticks(void)
604 if (cpu_ticks_enabled) {
605 cpu_ticks_offset = cpu_get_ticks();
606 cpu_ticks_enabled = 0;
611 void cpu_calibrate_ticks(void)
616 ret = QueryPerformanceFrequency(&freq);
618 fprintf(stderr, "Could not calibrate ticks\n");
621 ticks_per_sec = freq.QuadPart;
625 static int64_t get_clock(void)
628 gettimeofday(&tv, NULL);
629 return tv.tv_sec * 1000000LL + tv.tv_usec;
632 void cpu_calibrate_ticks(void)
637 ticks = cpu_get_real_ticks();
639 usec = get_clock() - usec;
640 ticks = cpu_get_real_ticks() - ticks;
641 ticks_per_sec = (ticks * 1000000LL + (usec >> 1)) / usec;
645 /* compute with 96 bit intermediate result: (a*b)/c */
646 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
651 #ifdef WORDS_BIGENDIAN
661 rl = (uint64_t)u.l.low * (uint64_t)b;
662 rh = (uint64_t)u.l.high * (uint64_t)b;
665 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
669 #define QEMU_TIMER_REALTIME 0
670 #define QEMU_TIMER_VIRTUAL 1
674 /* XXX: add frequency */
682 struct QEMUTimer *next;
688 static QEMUTimer *active_timers[2];
690 static MMRESULT timerID;
691 static HANDLE host_alarm = NULL;
692 static unsigned int period = 1;
694 /* frequency of the times() clock tick */
695 static int timer_freq;
698 QEMUClock *qemu_new_clock(int type)
701 clock = qemu_mallocz(sizeof(QEMUClock));
708 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
712 ts = qemu_mallocz(sizeof(QEMUTimer));
719 void qemu_free_timer(QEMUTimer *ts)
724 /* stop a timer, but do not dealloc it */
725 void qemu_del_timer(QEMUTimer *ts)
729 /* NOTE: this code must be signal safe because
730 qemu_timer_expired() can be called from a signal. */
731 pt = &active_timers[ts->clock->type];
744 /* modify the current timer so that it will be fired when current_time
745 >= expire_time. The corresponding callback will be called. */
746 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
752 /* add the timer in the sorted list */
753 /* NOTE: this code must be signal safe because
754 qemu_timer_expired() can be called from a signal. */
755 pt = &active_timers[ts->clock->type];
760 if (t->expire_time > expire_time)
764 ts->expire_time = expire_time;
769 int qemu_timer_pending(QEMUTimer *ts)
772 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
779 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
783 return (timer_head->expire_time <= current_time);
786 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
792 if (!ts || ts->expire_time > current_time)
794 /* remove timer from the list before calling the callback */
795 *ptimer_head = ts->next;
798 /* run the callback (the timer list can be modified) */
803 int64_t qemu_get_clock(QEMUClock *clock)
805 switch(clock->type) {
806 case QEMU_TIMER_REALTIME:
808 return GetTickCount();
813 /* Note that using gettimeofday() is not a good solution
814 for timers because its value change when the date is
816 if (timer_freq == 100) {
817 return times(&tp) * 10;
819 return ((int64_t)times(&tp) * 1000) / timer_freq;
824 case QEMU_TIMER_VIRTUAL:
825 return cpu_get_ticks();
830 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
832 uint64_t expire_time;
834 if (qemu_timer_pending(ts)) {
835 expire_time = ts->expire_time;
839 qemu_put_be64(f, expire_time);
842 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
844 uint64_t expire_time;
846 expire_time = qemu_get_be64(f);
847 if (expire_time != -1) {
848 qemu_mod_timer(ts, expire_time);
854 static void timer_save(QEMUFile *f, void *opaque)
856 if (cpu_ticks_enabled) {
857 hw_error("cannot save state if virtual timers are running");
859 qemu_put_be64s(f, &cpu_ticks_offset);
860 qemu_put_be64s(f, &ticks_per_sec);
863 static int timer_load(QEMUFile *f, void *opaque, int version_id)
867 if (cpu_ticks_enabled) {
870 qemu_get_be64s(f, &cpu_ticks_offset);
871 qemu_get_be64s(f, &ticks_per_sec);
876 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
877 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
879 static void host_alarm_handler(int host_signum)
883 #define DISP_FREQ 1000
885 static int64_t delta_min = INT64_MAX;
886 static int64_t delta_max, delta_cum, last_clock, delta, ti;
888 ti = qemu_get_clock(vm_clock);
889 if (last_clock != 0) {
890 delta = ti - last_clock;
891 if (delta < delta_min)
893 if (delta > delta_max)
896 if (++count == DISP_FREQ) {
897 printf("timer: min=%lld us max=%lld us avg=%lld us avg_freq=%0.3f Hz\n",
898 muldiv64(delta_min, 1000000, ticks_per_sec),
899 muldiv64(delta_max, 1000000, ticks_per_sec),
900 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
901 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
903 delta_min = INT64_MAX;
911 if (qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
912 qemu_get_clock(vm_clock)) ||
913 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
914 qemu_get_clock(rt_clock))) {
916 SetEvent(host_alarm);
918 CPUState *env = cpu_single_env;
920 /* stop the currently executing cpu because a timer occured */
921 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
923 if (env->kqemu_enabled) {
924 kqemu_cpu_interrupt(env);
933 #if defined(__linux__)
935 #define RTC_FREQ 1024
939 static int start_rtc_timer(void)
941 rtc_fd = open("/dev/rtc", O_RDONLY);
944 if (ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
945 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
946 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
947 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
950 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
955 pit_min_timer_count = PIT_FREQ / RTC_FREQ;
961 static int start_rtc_timer(void)
966 #endif /* !defined(__linux__) */
968 #endif /* !defined(_WIN32) */
970 static void init_timers(void)
972 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
973 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
980 ZeroMemory(&tc, sizeof(TIMECAPS));
981 timeGetDevCaps(&tc, sizeof(TIMECAPS));
982 if (period < tc.wPeriodMin)
983 period = tc.wPeriodMin;
984 timeBeginPeriod(period);
985 timerID = timeSetEvent(1, // interval (ms)
986 period, // resolution
987 host_alarm_handler, // function
988 (DWORD)&count, // user parameter
989 TIME_PERIODIC | TIME_CALLBACK_FUNCTION);
991 perror("failed timer alarm");
994 host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
996 perror("failed CreateEvent");
999 ResetEvent(host_alarm);
1001 pit_min_timer_count = ((uint64_t)10000 * PIT_FREQ) / 1000000;
1004 struct sigaction act;
1005 struct itimerval itv;
1007 /* get times() syscall frequency */
1008 timer_freq = sysconf(_SC_CLK_TCK);
1011 sigfillset(&act.sa_mask);
1013 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
1014 act.sa_flags |= SA_ONSTACK;
1016 act.sa_handler = host_alarm_handler;
1017 sigaction(SIGALRM, &act, NULL);
1019 itv.it_interval.tv_sec = 0;
1020 itv.it_interval.tv_usec = 999; /* for i386 kernel 2.6 to get 1 ms */
1021 itv.it_value.tv_sec = 0;
1022 itv.it_value.tv_usec = 10 * 1000;
1023 setitimer(ITIMER_REAL, &itv, NULL);
1024 /* we probe the tick duration of the kernel to inform the user if
1025 the emulated kernel requested a too high timer frequency */
1026 getitimer(ITIMER_REAL, &itv);
1028 #if defined(__linux__)
1029 /* XXX: force /dev/rtc usage because even 2.6 kernels may not
1030 have timers with 1 ms resolution. The correct solution will
1031 be to use the POSIX real time timers available in recent
1033 if (itv.it_interval.tv_usec > 1000 || 1) {
1034 /* try to use /dev/rtc to have a faster timer */
1035 if (start_rtc_timer() < 0)
1037 /* disable itimer */
1038 itv.it_interval.tv_sec = 0;
1039 itv.it_interval.tv_usec = 0;
1040 itv.it_value.tv_sec = 0;
1041 itv.it_value.tv_usec = 0;
1042 setitimer(ITIMER_REAL, &itv, NULL);
1045 sigaction(SIGIO, &act, NULL);
1046 fcntl(rtc_fd, F_SETFL, O_ASYNC);
1047 fcntl(rtc_fd, F_SETOWN, getpid());
1049 #endif /* defined(__linux__) */
1052 pit_min_timer_count = ((uint64_t)itv.it_interval.tv_usec *
1053 PIT_FREQ) / 1000000;
1059 void quit_timers(void)
1062 timeKillEvent(timerID);
1063 timeEndPeriod(period);
1065 CloseHandle(host_alarm);
1071 /***********************************************************/
1072 /* character device */
1074 int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1076 return s->chr_write(s, buf, len);
1079 int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1083 return s->chr_ioctl(s, cmd, arg);
1086 void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1091 vsnprintf(buf, sizeof(buf), fmt, ap);
1092 qemu_chr_write(s, buf, strlen(buf));
1096 void qemu_chr_send_event(CharDriverState *s, int event)
1098 if (s->chr_send_event)
1099 s->chr_send_event(s, event);
1102 void qemu_chr_add_read_handler(CharDriverState *s,
1103 IOCanRWHandler *fd_can_read,
1104 IOReadHandler *fd_read, void *opaque)
1106 s->chr_add_read_handler(s, fd_can_read, fd_read, opaque);
1109 void qemu_chr_add_event_handler(CharDriverState *s, IOEventHandler *chr_event)
1111 s->chr_event = chr_event;
1114 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1119 static void null_chr_add_read_handler(CharDriverState *chr,
1120 IOCanRWHandler *fd_can_read,
1121 IOReadHandler *fd_read, void *opaque)
1125 CharDriverState *qemu_chr_open_null(void)
1127 CharDriverState *chr;
1129 chr = qemu_mallocz(sizeof(CharDriverState));
1132 chr->chr_write = null_chr_write;
1133 chr->chr_add_read_handler = null_chr_add_read_handler;
1139 static void socket_cleanup(void)
1144 static int socket_init(void)
1149 ret = WSAStartup(MAKEWORD(2,2), &Data);
1151 err = WSAGetLastError();
1152 fprintf(stderr, "WSAStartup: %d\n", err);
1155 atexit(socket_cleanup);
1159 static int send_all(int fd, const uint8_t *buf, int len1)
1165 ret = send(fd, buf, len, 0);
1168 errno = WSAGetLastError();
1169 if (errno != WSAEWOULDBLOCK) {
1172 } else if (ret == 0) {
1182 void socket_set_nonblock(int fd)
1184 unsigned long opt = 1;
1185 ioctlsocket(fd, FIONBIO, &opt);
1190 static int unix_write(int fd, const uint8_t *buf, int len1)
1196 ret = write(fd, buf, len);
1198 if (errno != EINTR && errno != EAGAIN)
1200 } else if (ret == 0) {
1210 static inline int send_all(int fd, const uint8_t *buf, int len1)
1212 return unix_write(fd, buf, len1);
1215 void socket_set_nonblock(int fd)
1217 fcntl(fd, F_SETFL, O_NONBLOCK);
1219 #endif /* !_WIN32 */
1225 IOCanRWHandler *fd_can_read;
1226 IOReadHandler *fd_read;
1231 #define STDIO_MAX_CLIENTS 2
1233 static int stdio_nb_clients;
1234 static CharDriverState *stdio_clients[STDIO_MAX_CLIENTS];
1236 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1238 FDCharDriver *s = chr->opaque;
1239 return unix_write(s->fd_out, buf, len);
1242 static int fd_chr_read_poll(void *opaque)
1244 CharDriverState *chr = opaque;
1245 FDCharDriver *s = chr->opaque;
1247 s->max_size = s->fd_can_read(s->fd_opaque);
1251 static void fd_chr_read(void *opaque)
1253 CharDriverState *chr = opaque;
1254 FDCharDriver *s = chr->opaque;
1259 if (len > s->max_size)
1263 size = read(s->fd_in, buf, len);
1265 s->fd_read(s->fd_opaque, buf, size);
1269 static void fd_chr_add_read_handler(CharDriverState *chr,
1270 IOCanRWHandler *fd_can_read,
1271 IOReadHandler *fd_read, void *opaque)
1273 FDCharDriver *s = chr->opaque;
1275 if (s->fd_in >= 0) {
1276 s->fd_can_read = fd_can_read;
1277 s->fd_read = fd_read;
1278 s->fd_opaque = opaque;
1279 if (nographic && s->fd_in == 0) {
1281 qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
1282 fd_chr_read, NULL, chr);
1287 /* open a character device to a unix fd */
1288 CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
1290 CharDriverState *chr;
1293 chr = qemu_mallocz(sizeof(CharDriverState));
1296 s = qemu_mallocz(sizeof(FDCharDriver));
1304 chr->chr_write = fd_chr_write;
1305 chr->chr_add_read_handler = fd_chr_add_read_handler;
1309 CharDriverState *qemu_chr_open_file_out(const char *file_out)
1313 fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666);
1316 return qemu_chr_open_fd(-1, fd_out);
1319 CharDriverState *qemu_chr_open_pipe(const char *filename)
1323 fd = open(filename, O_RDWR | O_BINARY);
1326 return qemu_chr_open_fd(fd, fd);
1330 /* for STDIO, we handle the case where several clients use it
1333 #define TERM_ESCAPE 0x01 /* ctrl-a is used for escape */
1335 #define TERM_FIFO_MAX_SIZE 1
1337 static int term_got_escape, client_index;
1338 static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
1341 void term_print_help(void)
1344 "C-a h print this help\n"
1345 "C-a x exit emulator\n"
1346 "C-a s save disk data back to file (if -snapshot)\n"
1347 "C-a b send break (magic sysrq)\n"
1348 "C-a c switch between console and monitor\n"
1349 "C-a C-a send C-a\n"
1353 /* called when a char is received */
1354 static void stdio_received_byte(int ch)
1356 if (term_got_escape) {
1357 term_got_escape = 0;
1368 for (i = 0; i < MAX_DISKS; i++) {
1370 bdrv_commit(bs_table[i]);
1375 if (client_index < stdio_nb_clients) {
1376 CharDriverState *chr;
1379 chr = stdio_clients[client_index];
1381 chr->chr_event(s->fd_opaque, CHR_EVENT_BREAK);
1386 if (client_index >= stdio_nb_clients)
1388 if (client_index == 0) {
1389 /* send a new line in the monitor to get the prompt */
1397 } else if (ch == TERM_ESCAPE) {
1398 term_got_escape = 1;
1401 if (client_index < stdio_nb_clients) {
1403 CharDriverState *chr;
1406 chr = stdio_clients[client_index];
1408 if (s->fd_can_read(s->fd_opaque) > 0) {
1410 s->fd_read(s->fd_opaque, buf, 1);
1411 } else if (term_fifo_size == 0) {
1412 term_fifo[term_fifo_size++] = ch;
1418 static int stdio_read_poll(void *opaque)
1420 CharDriverState *chr;
1423 if (client_index < stdio_nb_clients) {
1424 chr = stdio_clients[client_index];
1426 /* try to flush the queue if needed */
1427 if (term_fifo_size != 0 && s->fd_can_read(s->fd_opaque) > 0) {
1428 s->fd_read(s->fd_opaque, term_fifo, 1);
1431 /* see if we can absorb more chars */
1432 if (term_fifo_size == 0)
1441 static void stdio_read(void *opaque)
1446 size = read(0, buf, 1);
1448 stdio_received_byte(buf[0]);
1451 /* init terminal so that we can grab keys */
1452 static struct termios oldtty;
1453 static int old_fd0_flags;
1455 static void term_exit(void)
1457 tcsetattr (0, TCSANOW, &oldtty);
1458 fcntl(0, F_SETFL, old_fd0_flags);
1461 static void term_init(void)
1465 tcgetattr (0, &tty);
1467 old_fd0_flags = fcntl(0, F_GETFL);
1469 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1470 |INLCR|IGNCR|ICRNL|IXON);
1471 tty.c_oflag |= OPOST;
1472 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1473 /* if graphical mode, we allow Ctrl-C handling */
1475 tty.c_lflag &= ~ISIG;
1476 tty.c_cflag &= ~(CSIZE|PARENB);
1479 tty.c_cc[VTIME] = 0;
1481 tcsetattr (0, TCSANOW, &tty);
1485 fcntl(0, F_SETFL, O_NONBLOCK);
1488 CharDriverState *qemu_chr_open_stdio(void)
1490 CharDriverState *chr;
1493 if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
1495 chr = qemu_chr_open_fd(0, 1);
1496 if (stdio_nb_clients == 0)
1497 qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, NULL);
1498 client_index = stdio_nb_clients;
1500 if (stdio_nb_clients != 0)
1502 chr = qemu_chr_open_fd(0, 1);
1504 stdio_clients[stdio_nb_clients++] = chr;
1505 if (stdio_nb_clients == 1) {
1506 /* set the terminal in raw mode */
1512 #if defined(__linux__)
1513 CharDriverState *qemu_chr_open_pty(void)
1516 char slave_name[1024];
1517 int master_fd, slave_fd;
1519 /* Not satisfying */
1520 if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
1524 /* Disabling local echo and line-buffered output */
1525 tcgetattr (master_fd, &tty);
1526 tty.c_lflag &= ~(ECHO|ICANON|ISIG);
1528 tty.c_cc[VTIME] = 0;
1529 tcsetattr (master_fd, TCSAFLUSH, &tty);
1531 fprintf(stderr, "char device redirected to %s\n", slave_name);
1532 return qemu_chr_open_fd(master_fd, master_fd);
1535 static void tty_serial_init(int fd, int speed,
1536 int parity, int data_bits, int stop_bits)
1542 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1543 speed, parity, data_bits, stop_bits);
1545 tcgetattr (fd, &tty);
1587 cfsetispeed(&tty, spd);
1588 cfsetospeed(&tty, spd);
1590 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1591 |INLCR|IGNCR|ICRNL|IXON);
1592 tty.c_oflag |= OPOST;
1593 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1594 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS);
1615 tty.c_cflag |= PARENB;
1618 tty.c_cflag |= PARENB | PARODD;
1622 tcsetattr (fd, TCSANOW, &tty);
1625 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1627 FDCharDriver *s = chr->opaque;
1630 case CHR_IOCTL_SERIAL_SET_PARAMS:
1632 QEMUSerialSetParams *ssp = arg;
1633 tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
1634 ssp->data_bits, ssp->stop_bits);
1637 case CHR_IOCTL_SERIAL_SET_BREAK:
1639 int enable = *(int *)arg;
1641 tcsendbreak(s->fd_in, 1);
1650 CharDriverState *qemu_chr_open_tty(const char *filename)
1652 CharDriverState *chr;
1655 fd = open(filename, O_RDWR | O_NONBLOCK);
1658 fcntl(fd, F_SETFL, O_NONBLOCK);
1659 tty_serial_init(fd, 115200, 'N', 8, 1);
1660 chr = qemu_chr_open_fd(fd, fd);
1663 chr->chr_ioctl = tty_serial_ioctl;
1667 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1669 int fd = (int)chr->opaque;
1673 case CHR_IOCTL_PP_READ_DATA:
1674 if (ioctl(fd, PPRDATA, &b) < 0)
1676 *(uint8_t *)arg = b;
1678 case CHR_IOCTL_PP_WRITE_DATA:
1679 b = *(uint8_t *)arg;
1680 if (ioctl(fd, PPWDATA, &b) < 0)
1683 case CHR_IOCTL_PP_READ_CONTROL:
1684 if (ioctl(fd, PPRCONTROL, &b) < 0)
1686 *(uint8_t *)arg = b;
1688 case CHR_IOCTL_PP_WRITE_CONTROL:
1689 b = *(uint8_t *)arg;
1690 if (ioctl(fd, PPWCONTROL, &b) < 0)
1693 case CHR_IOCTL_PP_READ_STATUS:
1694 if (ioctl(fd, PPRSTATUS, &b) < 0)
1696 *(uint8_t *)arg = b;
1704 CharDriverState *qemu_chr_open_pp(const char *filename)
1706 CharDriverState *chr;
1709 fd = open(filename, O_RDWR);
1713 if (ioctl(fd, PPCLAIM) < 0) {
1718 chr = qemu_mallocz(sizeof(CharDriverState));
1723 chr->opaque = (void *)fd;
1724 chr->chr_write = null_chr_write;
1725 chr->chr_add_read_handler = null_chr_add_read_handler;
1726 chr->chr_ioctl = pp_ioctl;
1731 CharDriverState *qemu_chr_open_pty(void)
1737 #endif /* !defined(_WIN32) */
1741 IOCanRWHandler *fd_can_read;
1742 IOReadHandler *fd_read;
1745 HANDLE hcom, hrecv, hsend;
1746 OVERLAPPED orecv, osend;
1751 #define NSENDBUF 2048
1752 #define NRECVBUF 2048
1753 #define MAXCONNECT 1
1754 #define NTIMEOUT 5000
1756 static int win_chr_poll(void *opaque);
1757 static int win_chr_pipe_poll(void *opaque);
1759 static void win_chr_close2(WinCharState *s)
1762 CloseHandle(s->hsend);
1766 CloseHandle(s->hrecv);
1770 CloseHandle(s->hcom);
1774 qemu_del_polling_cb(win_chr_pipe_poll, s);
1776 qemu_del_polling_cb(win_chr_poll, s);
1779 static void win_chr_close(CharDriverState *chr)
1781 WinCharState *s = chr->opaque;
1785 static int win_chr_init(WinCharState *s, const char *filename)
1788 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
1793 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1795 fprintf(stderr, "Failed CreateEvent\n");
1798 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1800 fprintf(stderr, "Failed CreateEvent\n");
1804 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
1805 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
1806 if (s->hcom == INVALID_HANDLE_VALUE) {
1807 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
1812 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
1813 fprintf(stderr, "Failed SetupComm\n");
1817 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
1818 size = sizeof(COMMCONFIG);
1819 GetDefaultCommConfig(filename, &comcfg, &size);
1820 comcfg.dcb.DCBlength = sizeof(DCB);
1821 CommConfigDialog(filename, NULL, &comcfg);
1823 if (!SetCommState(s->hcom, &comcfg.dcb)) {
1824 fprintf(stderr, "Failed SetCommState\n");
1828 if (!SetCommMask(s->hcom, EV_ERR)) {
1829 fprintf(stderr, "Failed SetCommMask\n");
1833 cto.ReadIntervalTimeout = MAXDWORD;
1834 if (!SetCommTimeouts(s->hcom, &cto)) {
1835 fprintf(stderr, "Failed SetCommTimeouts\n");
1839 if (!ClearCommError(s->hcom, &err, &comstat)) {
1840 fprintf(stderr, "Failed ClearCommError\n");
1843 qemu_add_polling_cb(win_chr_poll, s);
1851 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
1853 WinCharState *s = chr->opaque;
1854 DWORD len, ret, size, err;
1857 ZeroMemory(&s->osend, sizeof(s->osend));
1858 s->osend.hEvent = s->hsend;
1861 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
1863 ret = WriteFile(s->hcom, buf, len, &size, NULL);
1865 err = GetLastError();
1866 if (err == ERROR_IO_PENDING) {
1867 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
1885 static int win_chr_read_poll(WinCharState *s)
1887 s->max_size = s->fd_can_read(s->win_opaque);
1891 static void win_chr_readfile(WinCharState *s)
1897 ZeroMemory(&s->orecv, sizeof(s->orecv));
1898 s->orecv.hEvent = s->hrecv;
1899 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
1901 err = GetLastError();
1902 if (err == ERROR_IO_PENDING) {
1903 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
1908 s->fd_read(s->win_opaque, buf, size);
1912 static void win_chr_read(WinCharState *s)
1914 if (s->len > s->max_size)
1915 s->len = s->max_size;
1919 win_chr_readfile(s);
1922 static int win_chr_poll(void *opaque)
1924 WinCharState *s = opaque;
1928 ClearCommError(s->hcom, &comerr, &status);
1929 if (status.cbInQue > 0) {
1930 s->len = status.cbInQue;
1931 win_chr_read_poll(s);
1938 static void win_chr_add_read_handler(CharDriverState *chr,
1939 IOCanRWHandler *fd_can_read,
1940 IOReadHandler *fd_read, void *opaque)
1942 WinCharState *s = chr->opaque;
1944 s->fd_can_read = fd_can_read;
1945 s->fd_read = fd_read;
1946 s->win_opaque = opaque;
1949 CharDriverState *qemu_chr_open_win(const char *filename)
1951 CharDriverState *chr;
1954 chr = qemu_mallocz(sizeof(CharDriverState));
1957 s = qemu_mallocz(sizeof(WinCharState));
1963 chr->chr_write = win_chr_write;
1964 chr->chr_add_read_handler = win_chr_add_read_handler;
1965 chr->chr_close = win_chr_close;
1967 if (win_chr_init(s, filename) < 0) {
1975 static int win_chr_pipe_poll(void *opaque)
1977 WinCharState *s = opaque;
1980 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
1983 win_chr_read_poll(s);
1990 static int win_chr_pipe_init(WinCharState *s, const char *filename)
1999 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2001 fprintf(stderr, "Failed CreateEvent\n");
2004 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2006 fprintf(stderr, "Failed CreateEvent\n");
2010 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
2011 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2012 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
2014 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2015 if (s->hcom == INVALID_HANDLE_VALUE) {
2016 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
2021 ZeroMemory(&ov, sizeof(ov));
2022 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2023 ret = ConnectNamedPipe(s->hcom, &ov);
2025 fprintf(stderr, "Failed ConnectNamedPipe\n");
2029 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2031 fprintf(stderr, "Failed GetOverlappedResult\n");
2033 CloseHandle(ov.hEvent);
2040 CloseHandle(ov.hEvent);
2043 qemu_add_polling_cb(win_chr_pipe_poll, s);
2052 CharDriverState *qemu_chr_open_win_pipe(const char *filename)
2054 CharDriverState *chr;
2057 chr = qemu_mallocz(sizeof(CharDriverState));
2060 s = qemu_mallocz(sizeof(WinCharState));
2066 chr->chr_write = win_chr_write;
2067 chr->chr_add_read_handler = win_chr_add_read_handler;
2068 chr->chr_close = win_chr_close;
2070 if (win_chr_pipe_init(s, filename) < 0) {
2078 CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
2080 CharDriverState *chr;
2083 chr = qemu_mallocz(sizeof(CharDriverState));
2086 s = qemu_mallocz(sizeof(WinCharState));
2093 chr->chr_write = win_chr_write;
2094 chr->chr_add_read_handler = win_chr_add_read_handler;
2098 CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
2102 fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
2103 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2104 if (fd_out == INVALID_HANDLE_VALUE)
2107 return qemu_chr_open_win_file(fd_out);
2111 CharDriverState *qemu_chr_open(const char *filename)
2115 if (!strcmp(filename, "vc")) {
2116 return text_console_init(&display_state);
2117 } else if (!strcmp(filename, "null")) {
2118 return qemu_chr_open_null();
2121 if (strstart(filename, "file:", &p)) {
2122 return qemu_chr_open_file_out(p);
2123 } else if (strstart(filename, "pipe:", &p)) {
2124 return qemu_chr_open_pipe(p);
2125 } else if (!strcmp(filename, "pty")) {
2126 return qemu_chr_open_pty();
2127 } else if (!strcmp(filename, "stdio")) {
2128 return qemu_chr_open_stdio();
2131 #if defined(__linux__)
2132 if (strstart(filename, "/dev/parport", NULL)) {
2133 return qemu_chr_open_pp(filename);
2135 if (strstart(filename, "/dev/", NULL)) {
2136 return qemu_chr_open_tty(filename);
2140 if (strstart(filename, "COM", NULL)) {
2141 return qemu_chr_open_win(filename);
2143 if (strstart(filename, "pipe:", &p)) {
2144 return qemu_chr_open_win_pipe(p);
2146 if (strstart(filename, "file:", &p)) {
2147 return qemu_chr_open_win_file_out(p);
2155 void qemu_chr_close(CharDriverState *chr)
2158 chr->chr_close(chr);
2161 /***********************************************************/
2162 /* network device redirectors */
2164 void hex_dump(FILE *f, const uint8_t *buf, int size)
2168 for(i=0;i<size;i+=16) {
2172 fprintf(f, "%08x ", i);
2175 fprintf(f, " %02x", buf[i+j]);
2180 for(j=0;j<len;j++) {
2182 if (c < ' ' || c > '~')
2184 fprintf(f, "%c", c);
2190 static int parse_macaddr(uint8_t *macaddr, const char *p)
2193 for(i = 0; i < 6; i++) {
2194 macaddr[i] = strtol(p, (char **)&p, 16);
2207 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
2212 p1 = strchr(p, sep);
2218 if (len > buf_size - 1)
2220 memcpy(buf, p, len);
2227 int parse_host_port(struct sockaddr_in *saddr, const char *str)
2235 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2237 saddr->sin_family = AF_INET;
2238 if (buf[0] == '\0') {
2239 saddr->sin_addr.s_addr = 0;
2241 if (isdigit(buf[0])) {
2242 if (!inet_aton(buf, &saddr->sin_addr))
2245 if ((he = gethostbyname(buf)) == NULL)
2247 saddr->sin_addr = *(struct in_addr *)he->h_addr;
2250 port = strtol(p, (char **)&r, 0);
2253 saddr->sin_port = htons(port);
2257 /* find or alloc a new VLAN */
2258 VLANState *qemu_find_vlan(int id)
2260 VLANState **pvlan, *vlan;
2261 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
2265 vlan = qemu_mallocz(sizeof(VLANState));
2270 pvlan = &first_vlan;
2271 while (*pvlan != NULL)
2272 pvlan = &(*pvlan)->next;
2277 VLANClientState *qemu_new_vlan_client(VLANState *vlan,
2278 IOReadHandler *fd_read,
2279 IOCanRWHandler *fd_can_read,
2282 VLANClientState *vc, **pvc;
2283 vc = qemu_mallocz(sizeof(VLANClientState));
2286 vc->fd_read = fd_read;
2287 vc->fd_can_read = fd_can_read;
2288 vc->opaque = opaque;
2292 pvc = &vlan->first_client;
2293 while (*pvc != NULL)
2294 pvc = &(*pvc)->next;
2299 int qemu_can_send_packet(VLANClientState *vc1)
2301 VLANState *vlan = vc1->vlan;
2302 VLANClientState *vc;
2304 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
2306 if (vc->fd_can_read && !vc->fd_can_read(vc->opaque))
2313 void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
2315 VLANState *vlan = vc1->vlan;
2316 VLANClientState *vc;
2319 printf("vlan %d send:\n", vlan->id);
2320 hex_dump(stdout, buf, size);
2322 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
2324 vc->fd_read(vc->opaque, buf, size);
2329 #if defined(CONFIG_SLIRP)
2331 /* slirp network adapter */
2333 static int slirp_inited;
2334 static VLANClientState *slirp_vc;
2336 int slirp_can_output(void)
2338 return !slirp_vc || qemu_can_send_packet(slirp_vc);
2341 void slirp_output(const uint8_t *pkt, int pkt_len)
2344 printf("slirp output:\n");
2345 hex_dump(stdout, pkt, pkt_len);
2349 qemu_send_packet(slirp_vc, pkt, pkt_len);
2352 static void slirp_receive(void *opaque, const uint8_t *buf, int size)
2355 printf("slirp input:\n");
2356 hex_dump(stdout, buf, size);
2358 slirp_input(buf, size);
2361 static int net_slirp_init(VLANState *vlan)
2363 if (!slirp_inited) {
2367 slirp_vc = qemu_new_vlan_client(vlan,
2368 slirp_receive, NULL, NULL);
2369 snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
2373 static void net_slirp_redir(const char *redir_str)
2378 struct in_addr guest_addr;
2379 int host_port, guest_port;
2381 if (!slirp_inited) {
2387 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2389 if (!strcmp(buf, "tcp")) {
2391 } else if (!strcmp(buf, "udp")) {
2397 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2399 host_port = strtol(buf, &r, 0);
2403 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2405 if (buf[0] == '\0') {
2406 pstrcpy(buf, sizeof(buf), "10.0.2.15");
2408 if (!inet_aton(buf, &guest_addr))
2411 guest_port = strtol(p, &r, 0);
2415 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
2416 fprintf(stderr, "qemu: could not set up redirection\n");
2421 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
2429 static void smb_exit(void)
2433 char filename[1024];
2435 /* erase all the files in the directory */
2436 d = opendir(smb_dir);
2441 if (strcmp(de->d_name, ".") != 0 &&
2442 strcmp(de->d_name, "..") != 0) {
2443 snprintf(filename, sizeof(filename), "%s/%s",
2444 smb_dir, de->d_name);
2452 /* automatic user mode samba server configuration */
2453 void net_slirp_smb(const char *exported_dir)
2455 char smb_conf[1024];
2456 char smb_cmdline[1024];
2459 if (!slirp_inited) {
2464 /* XXX: better tmp dir construction */
2465 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
2466 if (mkdir(smb_dir, 0700) < 0) {
2467 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
2470 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
2472 f = fopen(smb_conf, "w");
2474 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
2481 "socket address=127.0.0.1\n"
2482 "pid directory=%s\n"
2483 "lock directory=%s\n"
2484 "log file=%s/log.smbd\n"
2485 "smb passwd file=%s/smbpasswd\n"
2486 "security = share\n"
2501 snprintf(smb_cmdline, sizeof(smb_cmdline), "/usr/sbin/smbd -s %s",
2504 slirp_add_exec(0, smb_cmdline, 4, 139);
2507 #endif /* !defined(_WIN32) */
2509 #endif /* CONFIG_SLIRP */
2511 #if !defined(_WIN32)
2513 typedef struct TAPState {
2514 VLANClientState *vc;
2518 static void tap_receive(void *opaque, const uint8_t *buf, int size)
2520 TAPState *s = opaque;
2523 ret = write(s->fd, buf, size);
2524 if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
2531 static void tap_send(void *opaque)
2533 TAPState *s = opaque;
2537 size = read(s->fd, buf, sizeof(buf));
2539 qemu_send_packet(s->vc, buf, size);
2545 static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
2549 s = qemu_mallocz(sizeof(TAPState));
2553 s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
2554 qemu_set_fd_handler(s->fd, tap_send, NULL, s);
2555 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
2560 static int tap_open(char *ifname, int ifname_size)
2566 fd = open("/dev/tap", O_RDWR);
2568 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
2573 dev = devname(s.st_rdev, S_IFCHR);
2574 pstrcpy(ifname, ifname_size, dev);
2576 fcntl(fd, F_SETFL, O_NONBLOCK);
2579 #elif defined(__sun__)
2580 static int tap_open(char *ifname, int ifname_size)
2582 fprintf(stderr, "warning: tap_open not yet implemented\n");
2586 static int tap_open(char *ifname, int ifname_size)
2591 fd = open("/dev/net/tun", O_RDWR);
2593 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
2596 memset(&ifr, 0, sizeof(ifr));
2597 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
2598 if (ifname[0] != '\0')
2599 pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
2601 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
2602 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
2604 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
2608 pstrcpy(ifname, ifname_size, ifr.ifr_name);
2609 fcntl(fd, F_SETFL, O_NONBLOCK);
2614 static int net_tap_init(VLANState *vlan, const char *ifname1,
2615 const char *setup_script)
2618 int pid, status, fd;
2623 if (ifname1 != NULL)
2624 pstrcpy(ifname, sizeof(ifname), ifname1);
2627 fd = tap_open(ifname, sizeof(ifname));
2633 if (setup_script[0] != '\0') {
2634 /* try to launch network init script */
2639 *parg++ = (char *)setup_script;
2642 execv(setup_script, args);
2645 while (waitpid(pid, &status, 0) != pid);
2646 if (!WIFEXITED(status) ||
2647 WEXITSTATUS(status) != 0) {
2648 fprintf(stderr, "%s: could not launch network script\n",
2654 s = net_tap_fd_init(vlan, fd);
2657 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
2658 "tap: ifname=%s setup_script=%s", ifname, setup_script);
2662 #endif /* !_WIN32 */
2664 /* network connection */
2665 typedef struct NetSocketState {
2666 VLANClientState *vc;
2668 int state; /* 0 = getting length, 1 = getting data */
2672 struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
2675 typedef struct NetSocketListenState {
2678 } NetSocketListenState;
2680 /* XXX: we consider we can send the whole packet without blocking */
2681 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
2683 NetSocketState *s = opaque;
2687 send_all(s->fd, (const uint8_t *)&len, sizeof(len));
2688 send_all(s->fd, buf, size);
2691 static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
2693 NetSocketState *s = opaque;
2694 sendto(s->fd, buf, size, 0,
2695 (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
2698 static void net_socket_send(void *opaque)
2700 NetSocketState *s = opaque;
2705 size = recv(s->fd, buf1, sizeof(buf1), 0);
2707 err = socket_error();
2708 if (err != EWOULDBLOCK)
2710 } else if (size == 0) {
2711 /* end of connection */
2713 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2719 /* reassemble a packet from the network */
2725 memcpy(s->buf + s->index, buf, l);
2729 if (s->index == 4) {
2731 s->packet_len = ntohl(*(uint32_t *)s->buf);
2737 l = s->packet_len - s->index;
2740 memcpy(s->buf + s->index, buf, l);
2744 if (s->index >= s->packet_len) {
2745 qemu_send_packet(s->vc, s->buf, s->packet_len);
2754 static void net_socket_send_dgram(void *opaque)
2756 NetSocketState *s = opaque;
2759 size = recv(s->fd, s->buf, sizeof(s->buf), 0);
2763 /* end of connection */
2764 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2767 qemu_send_packet(s->vc, s->buf, size);
2770 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
2775 if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
2776 fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
2777 inet_ntoa(mcastaddr->sin_addr),
2778 (int)ntohl(mcastaddr->sin_addr.s_addr));
2782 fd = socket(PF_INET, SOCK_DGRAM, 0);
2784 perror("socket(PF_INET, SOCK_DGRAM)");
2789 ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
2790 (const char *)&val, sizeof(val));
2792 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
2796 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
2802 /* Add host to multicast group */
2803 imr.imr_multiaddr = mcastaddr->sin_addr;
2804 imr.imr_interface.s_addr = htonl(INADDR_ANY);
2806 ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
2807 (const char *)&imr, sizeof(struct ip_mreq));
2809 perror("setsockopt(IP_ADD_MEMBERSHIP)");
2813 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
2815 ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
2816 (const char *)&val, sizeof(val));
2818 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
2822 socket_set_nonblock(fd);
2825 if (fd>=0) close(fd);
2829 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd,
2832 struct sockaddr_in saddr;
2834 socklen_t saddr_len;
2837 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
2838 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
2839 * by ONLY ONE process: we must "clone" this dgram socket --jjo
2843 if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
2845 if (saddr.sin_addr.s_addr==0) {
2846 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
2850 /* clone dgram socket */
2851 newfd = net_socket_mcast_create(&saddr);
2853 /* error already reported by net_socket_mcast_create() */
2857 /* clone newfd to fd, close newfd */
2862 fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
2863 fd, strerror(errno));
2868 s = qemu_mallocz(sizeof(NetSocketState));
2873 s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
2874 qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
2876 /* mcast: save bound address as dst */
2877 if (is_connected) s->dgram_dst=saddr;
2879 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
2880 "socket: fd=%d (%s mcast=%s:%d)",
2881 fd, is_connected? "cloned" : "",
2882 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
2886 static void net_socket_connect(void *opaque)
2888 NetSocketState *s = opaque;
2889 qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
2892 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd,
2896 s = qemu_mallocz(sizeof(NetSocketState));
2900 s->vc = qemu_new_vlan_client(vlan,
2901 net_socket_receive, NULL, s);
2902 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
2903 "socket: fd=%d", fd);
2905 net_socket_connect(s);
2907 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
2912 static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
2915 int so_type=-1, optlen=sizeof(so_type);
2917 if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type, &optlen)< 0) {
2918 fprintf(stderr, "qemu: error: setsockopt(SO_TYPE) for fd=%d failed\n", fd);
2923 return net_socket_fd_init_dgram(vlan, fd, is_connected);
2925 return net_socket_fd_init_stream(vlan, fd, is_connected);
2927 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
2928 fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
2929 return net_socket_fd_init_stream(vlan, fd, is_connected);
2934 static void net_socket_accept(void *opaque)
2936 NetSocketListenState *s = opaque;
2938 struct sockaddr_in saddr;
2943 len = sizeof(saddr);
2944 fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
2945 if (fd < 0 && errno != EINTR) {
2947 } else if (fd >= 0) {
2951 s1 = net_socket_fd_init(s->vlan, fd, 1);
2955 snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
2956 "socket: connection from %s:%d",
2957 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
2961 static int net_socket_listen_init(VLANState *vlan, const char *host_str)
2963 NetSocketListenState *s;
2965 struct sockaddr_in saddr;
2967 if (parse_host_port(&saddr, host_str) < 0)
2970 s = qemu_mallocz(sizeof(NetSocketListenState));
2974 fd = socket(PF_INET, SOCK_STREAM, 0);
2979 socket_set_nonblock(fd);
2981 /* allow fast reuse */
2983 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
2985 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
2990 ret = listen(fd, 0);
2997 qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
3001 static int net_socket_connect_init(VLANState *vlan, const char *host_str)
3004 int fd, connected, ret, err;
3005 struct sockaddr_in saddr;
3007 if (parse_host_port(&saddr, host_str) < 0)
3010 fd = socket(PF_INET, SOCK_STREAM, 0);
3015 socket_set_nonblock(fd);
3019 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
3021 err = socket_error();
3022 if (err == EINTR || err == EWOULDBLOCK) {
3023 } else if (err == EINPROGRESS) {
3035 s = net_socket_fd_init(vlan, fd, connected);
3038 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3039 "socket: connect to %s:%d",
3040 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3044 static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
3048 struct sockaddr_in saddr;
3050 if (parse_host_port(&saddr, host_str) < 0)
3054 fd = net_socket_mcast_create(&saddr);
3058 s = net_socket_fd_init(vlan, fd, 0);
3062 s->dgram_dst = saddr;
3064 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3065 "socket: mcast=%s:%d",
3066 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3071 static int get_param_value(char *buf, int buf_size,
3072 const char *tag, const char *str)
3081 while (*p != '\0' && *p != '=') {
3082 if ((q - option) < sizeof(option) - 1)
3090 if (!strcmp(tag, option)) {
3092 while (*p != '\0' && *p != ',') {
3093 if ((q - buf) < buf_size - 1)
3100 while (*p != '\0' && *p != ',') {
3111 int net_client_init(const char *str)
3122 while (*p != '\0' && *p != ',') {
3123 if ((q - device) < sizeof(device) - 1)
3131 if (get_param_value(buf, sizeof(buf), "vlan", p)) {
3132 vlan_id = strtol(buf, NULL, 0);
3134 vlan = qemu_find_vlan(vlan_id);
3136 fprintf(stderr, "Could not create vlan %d\n", vlan_id);
3139 if (!strcmp(device, "nic")) {
3143 if (nb_nics >= MAX_NICS) {
3144 fprintf(stderr, "Too Many NICs\n");
3147 nd = &nd_table[nb_nics];
3148 macaddr = nd->macaddr;
3154 macaddr[5] = 0x56 + nb_nics;
3156 if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
3157 if (parse_macaddr(macaddr, buf) < 0) {
3158 fprintf(stderr, "invalid syntax for ethernet address\n");
3162 if (get_param_value(buf, sizeof(buf), "model", p)) {
3163 nd->model = strdup(buf);
3169 if (!strcmp(device, "none")) {
3170 /* does nothing. It is needed to signal that no network cards
3175 if (!strcmp(device, "user")) {
3176 if (get_param_value(buf, sizeof(buf), "hostname", p)) {
3177 pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
3179 ret = net_slirp_init(vlan);
3183 if (!strcmp(device, "tap")) {
3185 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
3186 fprintf(stderr, "tap: no interface name\n");
3189 ret = tap_win32_init(vlan, ifname);
3192 if (!strcmp(device, "tap")) {
3194 char setup_script[1024];
3196 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
3197 fd = strtol(buf, NULL, 0);
3199 if (net_tap_fd_init(vlan, fd))
3202 get_param_value(ifname, sizeof(ifname), "ifname", p);
3203 if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
3204 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
3206 ret = net_tap_init(vlan, ifname, setup_script);
3210 if (!strcmp(device, "socket")) {
3211 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
3213 fd = strtol(buf, NULL, 0);
3215 if (net_socket_fd_init(vlan, fd, 1))
3217 } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
3218 ret = net_socket_listen_init(vlan, buf);
3219 } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
3220 ret = net_socket_connect_init(vlan, buf);
3221 } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
3222 ret = net_socket_mcast_init(vlan, buf);
3224 fprintf(stderr, "Unknown socket options: %s\n", p);
3229 fprintf(stderr, "Unknown network device: %s\n", device);
3233 fprintf(stderr, "Could not initialize device '%s'\n", device);
3239 void do_info_network(void)
3242 VLANClientState *vc;
3244 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
3245 term_printf("VLAN %d devices:\n", vlan->id);
3246 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
3247 term_printf(" %s\n", vc->info_str);
3251 /***********************************************************/
3254 static USBPort *used_usb_ports;
3255 static USBPort *free_usb_ports;
3257 /* ??? Maybe change this to register a hub to keep track of the topology. */
3258 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
3259 usb_attachfn attach)
3261 port->opaque = opaque;
3262 port->index = index;
3263 port->attach = attach;
3264 port->next = free_usb_ports;
3265 free_usb_ports = port;
3268 static int usb_device_add(const char *devname)
3274 if (!free_usb_ports)
3277 if (strstart(devname, "host:", &p)) {
3278 dev = usb_host_device_open(p);
3279 } else if (!strcmp(devname, "mouse")) {
3280 dev = usb_mouse_init();
3281 } else if (!strcmp(devname, "tablet")) {
3282 dev = usb_tablet_init();
3283 } else if (strstart(devname, "disk:", &p)) {
3284 dev = usb_msd_init(p);
3291 /* Find a USB port to add the device to. */
3292 port = free_usb_ports;
3296 /* Create a new hub and chain it on. */
3297 free_usb_ports = NULL;
3298 port->next = used_usb_ports;
3299 used_usb_ports = port;
3301 hub = usb_hub_init(VM_USB_HUB_SIZE);
3302 usb_attach(port, hub);
3303 port = free_usb_ports;
3306 free_usb_ports = port->next;
3307 port->next = used_usb_ports;
3308 used_usb_ports = port;
3309 usb_attach(port, dev);
3313 static int usb_device_del(const char *devname)
3320 if (!used_usb_ports)
3323 p = strchr(devname, '.');
3326 bus_num = strtoul(devname, NULL, 0);
3327 addr = strtoul(p + 1, NULL, 0);
3331 lastp = &used_usb_ports;
3332 port = used_usb_ports;
3333 while (port && port->dev->addr != addr) {
3334 lastp = &port->next;
3341 *lastp = port->next;
3342 usb_attach(port, NULL);
3343 port->next = free_usb_ports;
3344 free_usb_ports = port;
3348 void do_usb_add(const char *devname)
3351 ret = usb_device_add(devname);
3353 term_printf("Could not add USB device '%s'\n", devname);
3356 void do_usb_del(const char *devname)
3359 ret = usb_device_del(devname);
3361 term_printf("Could not remove USB device '%s'\n", devname);
3368 const char *speed_str;
3371 term_printf("USB support not enabled\n");
3375 for (port = used_usb_ports; port; port = port->next) {
3379 switch(dev->speed) {
3383 case USB_SPEED_FULL:
3386 case USB_SPEED_HIGH:
3393 term_printf(" Device %d.%d, speed %s Mb/s\n",
3394 0, dev->addr, speed_str);
3398 /***********************************************************/
3401 static char *pid_filename;
3403 /* Remove PID file. Called on normal exit */
3405 static void remove_pidfile(void)
3407 unlink (pid_filename);
3410 static void create_pidfile(const char *filename)
3412 struct stat pidstat;
3415 /* Try to write our PID to the named file */
3416 if (stat(filename, &pidstat) < 0) {
3417 if (errno == ENOENT) {
3418 if ((f = fopen (filename, "w")) == NULL) {
3419 perror("Opening pidfile");
3422 fprintf(f, "%d\n", getpid());
3424 pid_filename = qemu_strdup(filename);
3425 if (!pid_filename) {
3426 fprintf(stderr, "Could not save PID filename");
3429 atexit(remove_pidfile);
3432 fprintf(stderr, "%s already exists. Remove it and try again.\n",
3438 /***********************************************************/
3441 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
3445 static void dumb_resize(DisplayState *ds, int w, int h)
3449 static void dumb_refresh(DisplayState *ds)
3454 void dumb_display_init(DisplayState *ds)
3459 ds->dpy_update = dumb_update;
3460 ds->dpy_resize = dumb_resize;
3461 ds->dpy_refresh = dumb_refresh;
3464 #if !defined(CONFIG_SOFTMMU)
3465 /***********************************************************/
3466 /* cpu signal handler */
3467 static void host_segv_handler(int host_signum, siginfo_t *info,
3470 if (cpu_signal_handler(host_signum, info, puc))
3472 if (stdio_nb_clients > 0)
3478 /***********************************************************/
3481 #define MAX_IO_HANDLERS 64
3483 typedef struct IOHandlerRecord {
3485 IOCanRWHandler *fd_read_poll;
3487 IOHandler *fd_write;
3489 /* temporary data */
3491 struct IOHandlerRecord *next;
3494 static IOHandlerRecord *first_io_handler;
3496 /* XXX: fd_read_poll should be suppressed, but an API change is
3497 necessary in the character devices to suppress fd_can_read(). */
3498 int qemu_set_fd_handler2(int fd,
3499 IOCanRWHandler *fd_read_poll,
3501 IOHandler *fd_write,
3504 IOHandlerRecord **pioh, *ioh;
3506 if (!fd_read && !fd_write) {
3507 pioh = &first_io_handler;
3512 if (ioh->fd == fd) {
3520 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3524 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
3527 ioh->next = first_io_handler;
3528 first_io_handler = ioh;
3531 ioh->fd_read_poll = fd_read_poll;
3532 ioh->fd_read = fd_read;
3533 ioh->fd_write = fd_write;
3534 ioh->opaque = opaque;
3539 int qemu_set_fd_handler(int fd,
3541 IOHandler *fd_write,
3544 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
3547 /***********************************************************/
3548 /* Polling handling */
3550 typedef struct PollingEntry {
3553 struct PollingEntry *next;
3556 static PollingEntry *first_polling_entry;
3558 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
3560 PollingEntry **ppe, *pe;
3561 pe = qemu_mallocz(sizeof(PollingEntry));
3565 pe->opaque = opaque;
3566 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
3571 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
3573 PollingEntry **ppe, *pe;
3574 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
3576 if (pe->func == func && pe->opaque == opaque) {
3584 /***********************************************************/
3585 /* savevm/loadvm support */
3587 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
3589 fwrite(buf, 1, size, f);
3592 void qemu_put_byte(QEMUFile *f, int v)
3597 void qemu_put_be16(QEMUFile *f, unsigned int v)
3599 qemu_put_byte(f, v >> 8);
3600 qemu_put_byte(f, v);
3603 void qemu_put_be32(QEMUFile *f, unsigned int v)
3605 qemu_put_byte(f, v >> 24);
3606 qemu_put_byte(f, v >> 16);
3607 qemu_put_byte(f, v >> 8);
3608 qemu_put_byte(f, v);
3611 void qemu_put_be64(QEMUFile *f, uint64_t v)
3613 qemu_put_be32(f, v >> 32);
3614 qemu_put_be32(f, v);
3617 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size)
3619 return fread(buf, 1, size, f);
3622 int qemu_get_byte(QEMUFile *f)
3632 unsigned int qemu_get_be16(QEMUFile *f)
3635 v = qemu_get_byte(f) << 8;
3636 v |= qemu_get_byte(f);
3640 unsigned int qemu_get_be32(QEMUFile *f)
3643 v = qemu_get_byte(f) << 24;
3644 v |= qemu_get_byte(f) << 16;
3645 v |= qemu_get_byte(f) << 8;
3646 v |= qemu_get_byte(f);
3650 uint64_t qemu_get_be64(QEMUFile *f)
3653 v = (uint64_t)qemu_get_be32(f) << 32;
3654 v |= qemu_get_be32(f);
3658 int64_t qemu_ftell(QEMUFile *f)
3663 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
3665 if (fseek(f, pos, whence) < 0)
3670 typedef struct SaveStateEntry {
3674 SaveStateHandler *save_state;
3675 LoadStateHandler *load_state;
3677 struct SaveStateEntry *next;
3680 static SaveStateEntry *first_se;
3682 int register_savevm(const char *idstr,
3685 SaveStateHandler *save_state,
3686 LoadStateHandler *load_state,
3689 SaveStateEntry *se, **pse;
3691 se = qemu_malloc(sizeof(SaveStateEntry));
3694 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
3695 se->instance_id = instance_id;
3696 se->version_id = version_id;
3697 se->save_state = save_state;
3698 se->load_state = load_state;
3699 se->opaque = opaque;
3702 /* add at the end of list */
3704 while (*pse != NULL)
3705 pse = &(*pse)->next;
3710 #define QEMU_VM_FILE_MAGIC 0x5145564d
3711 #define QEMU_VM_FILE_VERSION 0x00000001
3713 int qemu_savevm(const char *filename)
3717 int len, len_pos, cur_pos, saved_vm_running, ret;
3719 saved_vm_running = vm_running;
3722 f = fopen(filename, "wb");
3728 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
3729 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
3731 for(se = first_se; se != NULL; se = se->next) {
3733 len = strlen(se->idstr);
3734 qemu_put_byte(f, len);
3735 qemu_put_buffer(f, se->idstr, len);
3737 qemu_put_be32(f, se->instance_id);
3738 qemu_put_be32(f, se->version_id);
3740 /* record size: filled later */
3742 qemu_put_be32(f, 0);
3744 se->save_state(f, se->opaque);
3746 /* fill record size */
3748 len = ftell(f) - len_pos - 4;
3749 fseek(f, len_pos, SEEK_SET);
3750 qemu_put_be32(f, len);
3751 fseek(f, cur_pos, SEEK_SET);
3757 if (saved_vm_running)
3762 static SaveStateEntry *find_se(const char *idstr, int instance_id)
3766 for(se = first_se; se != NULL; se = se->next) {
3767 if (!strcmp(se->idstr, idstr) &&
3768 instance_id == se->instance_id)
3774 int qemu_loadvm(const char *filename)
3778 int len, cur_pos, ret, instance_id, record_len, version_id;
3779 int saved_vm_running;
3783 saved_vm_running = vm_running;
3786 f = fopen(filename, "rb");
3792 v = qemu_get_be32(f);
3793 if (v != QEMU_VM_FILE_MAGIC)
3795 v = qemu_get_be32(f);
3796 if (v != QEMU_VM_FILE_VERSION) {
3803 len = qemu_get_byte(f);
3806 qemu_get_buffer(f, idstr, len);
3808 instance_id = qemu_get_be32(f);
3809 version_id = qemu_get_be32(f);
3810 record_len = qemu_get_be32(f);
3812 printf("idstr=%s instance=0x%x version=%d len=%d\n",
3813 idstr, instance_id, version_id, record_len);
3816 se = find_se(idstr, instance_id);
3818 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
3819 instance_id, idstr);
3821 ret = se->load_state(f, se->opaque, version_id);
3823 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
3824 instance_id, idstr);
3827 /* always seek to exact end of record */
3828 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
3833 if (saved_vm_running)
3838 /***********************************************************/
3839 /* cpu save/restore */
3841 #if defined(TARGET_I386)
3843 static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
3845 qemu_put_be32(f, dt->selector);
3846 qemu_put_betl(f, dt->base);
3847 qemu_put_be32(f, dt->limit);
3848 qemu_put_be32(f, dt->flags);
3851 static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
3853 dt->selector = qemu_get_be32(f);
3854 dt->base = qemu_get_betl(f);
3855 dt->limit = qemu_get_be32(f);
3856 dt->flags = qemu_get_be32(f);
3859 void cpu_save(QEMUFile *f, void *opaque)
3861 CPUState *env = opaque;
3862 uint16_t fptag, fpus, fpuc, fpregs_format;
3866 for(i = 0; i < CPU_NB_REGS; i++)
3867 qemu_put_betls(f, &env->regs[i]);
3868 qemu_put_betls(f, &env->eip);
3869 qemu_put_betls(f, &env->eflags);
3870 hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
3871 qemu_put_be32s(f, &hflags);
3875 fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
3877 for(i = 0; i < 8; i++) {
3878 fptag |= ((!env->fptags[i]) << i);
3881 qemu_put_be16s(f, &fpuc);
3882 qemu_put_be16s(f, &fpus);
3883 qemu_put_be16s(f, &fptag);
3885 #ifdef USE_X86LDOUBLE
3890 qemu_put_be16s(f, &fpregs_format);
3892 for(i = 0; i < 8; i++) {
3893 #ifdef USE_X86LDOUBLE
3897 /* we save the real CPU data (in case of MMX usage only 'mant'
3898 contains the MMX register */
3899 cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
3900 qemu_put_be64(f, mant);
3901 qemu_put_be16(f, exp);
3904 /* if we use doubles for float emulation, we save the doubles to
3905 avoid losing information in case of MMX usage. It can give
3906 problems if the image is restored on a CPU where long
3907 doubles are used instead. */
3908 qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
3912 for(i = 0; i < 6; i++)
3913 cpu_put_seg(f, &env->segs[i]);
3914 cpu_put_seg(f, &env->ldt);
3915 cpu_put_seg(f, &env->tr);
3916 cpu_put_seg(f, &env->gdt);
3917 cpu_put_seg(f, &env->idt);
3919 qemu_put_be32s(f, &env->sysenter_cs);
3920 qemu_put_be32s(f, &env->sysenter_esp);
3921 qemu_put_be32s(f, &env->sysenter_eip);
3923 qemu_put_betls(f, &env->cr[0]);
3924 qemu_put_betls(f, &env->cr[2]);
3925 qemu_put_betls(f, &env->cr[3]);
3926 qemu_put_betls(f, &env->cr[4]);
3928 for(i = 0; i < 8; i++)
3929 qemu_put_betls(f, &env->dr[i]);
3932 qemu_put_be32s(f, &env->a20_mask);
3935 qemu_put_be32s(f, &env->mxcsr);
3936 for(i = 0; i < CPU_NB_REGS; i++) {
3937 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
3938 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
3941 #ifdef TARGET_X86_64
3942 qemu_put_be64s(f, &env->efer);
3943 qemu_put_be64s(f, &env->star);
3944 qemu_put_be64s(f, &env->lstar);
3945 qemu_put_be64s(f, &env->cstar);
3946 qemu_put_be64s(f, &env->fmask);
3947 qemu_put_be64s(f, &env->kernelgsbase);
3951 #ifdef USE_X86LDOUBLE
3952 /* XXX: add that in a FPU generic layer */
3953 union x86_longdouble {
3958 #define MANTD1(fp) (fp & ((1LL << 52) - 1))
3959 #define EXPBIAS1 1023
3960 #define EXPD1(fp) ((fp >> 52) & 0x7FF)
3961 #define SIGND1(fp) ((fp >> 32) & 0x80000000)
3963 static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
3967 p->mant = (MANTD1(temp) << 11) | (1LL << 63);
3968 /* exponent + sign */
3969 e = EXPD1(temp) - EXPBIAS1 + 16383;
3970 e |= SIGND1(temp) >> 16;
3975 int cpu_load(QEMUFile *f, void *opaque, int version_id)
3977 CPUState *env = opaque;
3980 uint16_t fpus, fpuc, fptag, fpregs_format;
3982 if (version_id != 3)
3984 for(i = 0; i < CPU_NB_REGS; i++)
3985 qemu_get_betls(f, &env->regs[i]);
3986 qemu_get_betls(f, &env->eip);
3987 qemu_get_betls(f, &env->eflags);
3988 qemu_get_be32s(f, &hflags);
3990 qemu_get_be16s(f, &fpuc);
3991 qemu_get_be16s(f, &fpus);
3992 qemu_get_be16s(f, &fptag);
3993 qemu_get_be16s(f, &fpregs_format);
3995 /* NOTE: we cannot always restore the FPU state if the image come
3996 from a host with a different 'USE_X86LDOUBLE' define. We guess
3997 if we are in an MMX state to restore correctly in that case. */
3998 guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
3999 for(i = 0; i < 8; i++) {
4003 switch(fpregs_format) {
4005 mant = qemu_get_be64(f);
4006 exp = qemu_get_be16(f);
4007 #ifdef USE_X86LDOUBLE
4008 env->fpregs[i].d = cpu_set_fp80(mant, exp);
4010 /* difficult case */
4012 env->fpregs[i].mmx.MMX_Q(0) = mant;
4014 env->fpregs[i].d = cpu_set_fp80(mant, exp);
4018 mant = qemu_get_be64(f);
4019 #ifdef USE_X86LDOUBLE
4021 union x86_longdouble *p;
4022 /* difficult case */
4023 p = (void *)&env->fpregs[i];
4028 fp64_to_fp80(p, mant);
4032 env->fpregs[i].mmx.MMX_Q(0) = mant;
4041 /* XXX: restore FPU round state */
4042 env->fpstt = (fpus >> 11) & 7;
4043 env->fpus = fpus & ~0x3800;
4045 for(i = 0; i < 8; i++) {
4046 env->fptags[i] = (fptag >> i) & 1;
4049 for(i = 0; i < 6; i++)
4050 cpu_get_seg(f, &env->segs[i]);
4051 cpu_get_seg(f, &env->ldt);
4052 cpu_get_seg(f, &env->tr);
4053 cpu_get_seg(f, &env->gdt);
4054 cpu_get_seg(f, &env->idt);
4056 qemu_get_be32s(f, &env->sysenter_cs);
4057 qemu_get_be32s(f, &env->sysenter_esp);
4058 qemu_get_be32s(f, &env->sysenter_eip);
4060 qemu_get_betls(f, &env->cr[0]);
4061 qemu_get_betls(f, &env->cr[2]);
4062 qemu_get_betls(f, &env->cr[3]);
4063 qemu_get_betls(f, &env->cr[4]);
4065 for(i = 0; i < 8; i++)
4066 qemu_get_betls(f, &env->dr[i]);
4069 qemu_get_be32s(f, &env->a20_mask);
4071 qemu_get_be32s(f, &env->mxcsr);
4072 for(i = 0; i < CPU_NB_REGS; i++) {
4073 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
4074 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
4077 #ifdef TARGET_X86_64
4078 qemu_get_be64s(f, &env->efer);
4079 qemu_get_be64s(f, &env->star);
4080 qemu_get_be64s(f, &env->lstar);
4081 qemu_get_be64s(f, &env->cstar);
4082 qemu_get_be64s(f, &env->fmask);
4083 qemu_get_be64s(f, &env->kernelgsbase);
4086 /* XXX: compute hflags from scratch, except for CPL and IIF */
4087 env->hflags = hflags;
4092 #elif defined(TARGET_PPC)
4093 void cpu_save(QEMUFile *f, void *opaque)
4097 int cpu_load(QEMUFile *f, void *opaque, int version_id)
4102 #elif defined(TARGET_MIPS)
4103 void cpu_save(QEMUFile *f, void *opaque)
4107 int cpu_load(QEMUFile *f, void *opaque, int version_id)
4112 #elif defined(TARGET_SPARC)
4113 void cpu_save(QEMUFile *f, void *opaque)
4115 CPUState *env = opaque;
4119 for(i = 0; i < 8; i++)
4120 qemu_put_betls(f, &env->gregs[i]);
4121 for(i = 0; i < NWINDOWS * 16; i++)
4122 qemu_put_betls(f, &env->regbase[i]);
4125 for(i = 0; i < TARGET_FPREGS; i++) {
4131 qemu_put_betl(f, u.i);
4134 qemu_put_betls(f, &env->pc);
4135 qemu_put_betls(f, &env->npc);
4136 qemu_put_betls(f, &env->y);
4138 qemu_put_be32(f, tmp);
4139 qemu_put_betls(f, &env->fsr);
4140 qemu_put_betls(f, &env->tbr);
4141 #ifndef TARGET_SPARC64
4142 qemu_put_be32s(f, &env->wim);
4144 for(i = 0; i < 16; i++)
4145 qemu_put_be32s(f, &env->mmuregs[i]);
4149 int cpu_load(QEMUFile *f, void *opaque, int version_id)
4151 CPUState *env = opaque;
4155 for(i = 0; i < 8; i++)
4156 qemu_get_betls(f, &env->gregs[i]);
4157 for(i = 0; i < NWINDOWS * 16; i++)
4158 qemu_get_betls(f, &env->regbase[i]);
4161 for(i = 0; i < TARGET_FPREGS; i++) {
4166 u.i = qemu_get_betl(f);
4170 qemu_get_betls(f, &env->pc);
4171 qemu_get_betls(f, &env->npc);
4172 qemu_get_betls(f, &env->y);
4173 tmp = qemu_get_be32(f);
4174 env->cwp = 0; /* needed to ensure that the wrapping registers are
4175 correctly updated */
4177 qemu_get_betls(f, &env->fsr);
4178 qemu_get_betls(f, &env->tbr);
4179 #ifndef TARGET_SPARC64
4180 qemu_get_be32s(f, &env->wim);
4182 for(i = 0; i < 16; i++)
4183 qemu_get_be32s(f, &env->mmuregs[i]);
4189 #elif defined(TARGET_ARM)
4191 /* ??? Need to implement these. */
4192 void cpu_save(QEMUFile *f, void *opaque)
4196 int cpu_load(QEMUFile *f, void *opaque, int version_id)
4203 #warning No CPU save/restore functions
4207 /***********************************************************/
4208 /* ram save/restore */
4210 /* we just avoid storing empty pages */
4211 static void ram_put_page(QEMUFile *f, const uint8_t *buf, int len)
4216 for(i = 1; i < len; i++) {
4220 qemu_put_byte(f, 1);
4221 qemu_put_byte(f, v);
4224 qemu_put_byte(f, 0);
4225 qemu_put_buffer(f, buf, len);
4228 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
4232 v = qemu_get_byte(f);
4235 if (qemu_get_buffer(f, buf, len) != len)
4239 v = qemu_get_byte(f);
4240 memset(buf, v, len);
4248 static void ram_save(QEMUFile *f, void *opaque)
4251 qemu_put_be32(f, phys_ram_size);
4252 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
4253 ram_put_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
4257 static int ram_load(QEMUFile *f, void *opaque, int version_id)
4261 if (version_id != 1)
4263 if (qemu_get_be32(f) != phys_ram_size)
4265 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
4266 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
4273 /***********************************************************/
4274 /* machine registration */
4276 QEMUMachine *first_machine = NULL;
4278 int qemu_register_machine(QEMUMachine *m)
4281 pm = &first_machine;
4289 QEMUMachine *find_machine(const char *name)
4293 for(m = first_machine; m != NULL; m = m->next) {
4294 if (!strcmp(m->name, name))
4300 /***********************************************************/
4301 /* main execution loop */
4303 void gui_update(void *opaque)
4305 display_state.dpy_refresh(&display_state);
4306 qemu_mod_timer(gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
4309 struct vm_change_state_entry {
4310 VMChangeStateHandler *cb;
4312 LIST_ENTRY (vm_change_state_entry) entries;
4315 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
4317 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
4320 VMChangeStateEntry *e;
4322 e = qemu_mallocz(sizeof (*e));
4328 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
4332 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
4334 LIST_REMOVE (e, entries);
4338 static void vm_state_notify(int running)
4340 VMChangeStateEntry *e;
4342 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
4343 e->cb(e->opaque, running);
4347 /* XXX: support several handlers */
4348 static VMStopHandler *vm_stop_cb;
4349 static void *vm_stop_opaque;
4351 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
4354 vm_stop_opaque = opaque;
4358 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
4372 void vm_stop(int reason)
4375 cpu_disable_ticks();
4379 vm_stop_cb(vm_stop_opaque, reason);
4386 /* reset/shutdown handler */
4388 typedef struct QEMUResetEntry {
4389 QEMUResetHandler *func;
4391 struct QEMUResetEntry *next;
4394 static QEMUResetEntry *first_reset_entry;
4395 static int reset_requested;
4396 static int shutdown_requested;
4397 static int powerdown_requested;
4399 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
4401 QEMUResetEntry **pre, *re;
4403 pre = &first_reset_entry;
4404 while (*pre != NULL)
4405 pre = &(*pre)->next;
4406 re = qemu_mallocz(sizeof(QEMUResetEntry));
4408 re->opaque = opaque;
4413 void qemu_system_reset(void)
4417 /* reset all devices */
4418 for(re = first_reset_entry; re != NULL; re = re->next) {
4419 re->func(re->opaque);
4423 void qemu_system_reset_request(void)
4425 reset_requested = 1;
4427 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
4430 void qemu_system_shutdown_request(void)
4432 shutdown_requested = 1;
4434 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
4437 void qemu_system_powerdown_request(void)
4439 powerdown_requested = 1;
4441 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
4444 void main_loop_wait(int timeout)
4446 IOHandlerRecord *ioh, *ioh_next;
4447 fd_set rfds, wfds, xfds;
4453 /* XXX: need to suppress polling by better using win32 events */
4455 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
4456 ret |= pe->func(pe->opaque);
4459 if (ret == 0 && timeout > 0) {
4463 hEvents[0] = host_alarm;
4464 ret = WaitForMultipleObjects(1, hEvents, FALSE, timeout);
4466 case WAIT_OBJECT_0 + 0:
4471 err = GetLastError();
4472 fprintf(stderr, "Wait error %d %d\n", ret, err);
4477 /* poll any events */
4478 /* XXX: separate device handlers from system ones */
4483 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4485 (!ioh->fd_read_poll ||
4486 ioh->fd_read_poll(ioh->opaque) != 0)) {
4487 FD_SET(ioh->fd, &rfds);
4491 if (ioh->fd_write) {
4492 FD_SET(ioh->fd, &wfds);
4502 tv.tv_usec = timeout * 1000;
4504 #if defined(CONFIG_SLIRP)
4506 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
4509 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
4511 /* XXX: better handling of removal */
4512 for(ioh = first_io_handler; ioh != NULL; ioh = ioh_next) {
4513 ioh_next = ioh->next;
4514 if (FD_ISSET(ioh->fd, &rfds)) {
4515 ioh->fd_read(ioh->opaque);
4517 if (FD_ISSET(ioh->fd, &wfds)) {
4518 ioh->fd_write(ioh->opaque);
4522 #if defined(CONFIG_SLIRP)
4529 slirp_select_poll(&rfds, &wfds, &xfds);
4537 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
4538 qemu_get_clock(vm_clock));
4539 /* run dma transfers, if any */
4543 /* real time timers */
4544 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
4545 qemu_get_clock(rt_clock));
4548 static CPUState *cur_cpu;
4553 #ifdef CONFIG_PROFILER
4558 cur_cpu = first_cpu;
4565 env = env->next_cpu;
4568 #ifdef CONFIG_PROFILER
4569 ti = profile_getclock();
4571 ret = cpu_exec(env);
4572 #ifdef CONFIG_PROFILER
4573 qemu_time += profile_getclock() - ti;
4575 if (ret != EXCP_HALTED)
4577 /* all CPUs are halted ? */
4578 if (env == cur_cpu) {
4585 if (shutdown_requested) {
4586 ret = EXCP_INTERRUPT;
4589 if (reset_requested) {
4590 reset_requested = 0;
4591 qemu_system_reset();
4592 ret = EXCP_INTERRUPT;
4594 if (powerdown_requested) {
4595 powerdown_requested = 0;
4596 qemu_system_powerdown();
4597 ret = EXCP_INTERRUPT;
4599 if (ret == EXCP_DEBUG) {
4600 vm_stop(EXCP_DEBUG);
4602 /* if hlt instruction, we wait until the next IRQ */
4603 /* XXX: use timeout computed from timers */
4604 if (ret == EXCP_HLT)
4611 #ifdef CONFIG_PROFILER
4612 ti = profile_getclock();
4614 main_loop_wait(timeout);
4615 #ifdef CONFIG_PROFILER
4616 dev_time += profile_getclock() - ti;
4619 cpu_disable_ticks();
4625 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2005 Fabrice Bellard\n"
4626 "usage: %s [options] [disk_image]\n"
4628 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4630 "Standard options:\n"
4631 "-M machine select emulated machine (-M ? for list)\n"
4632 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
4633 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
4634 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
4635 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
4636 "-boot [a|c|d] boot on floppy (a), hard disk (c) or CD-ROM (d)\n"
4637 "-snapshot write to temporary files instead of disk image files\n"
4639 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
4641 "-m megs set virtual RAM size to megs MB [default=%d]\n"
4642 "-smp n set the number of CPUs to 'n' [default=1]\n"
4643 "-nographic disable graphical output and redirect serial I/Os to console\n"
4645 "-k language use keyboard layout (for example \"fr\" for French)\n"
4648 "-audio-help print list of audio drivers and their options\n"
4649 "-soundhw c1,... enable audio support\n"
4650 " and only specified sound cards (comma separated list)\n"
4651 " use -soundhw ? to get the list of supported cards\n"
4652 " use -soundhw all to enable all of them\n"
4654 "-localtime set the real time clock to local time [default=utc]\n"
4655 "-full-screen start in full screen\n"
4657 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
4659 "-usb enable the USB driver (will be the default soon)\n"
4660 "-usbdevice name add the host or guest USB device 'name'\n"
4661 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
4662 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
4665 "Network options:\n"
4666 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
4667 " create a new Network Interface Card and connect it to VLAN 'n'\n"
4669 "-net user[,vlan=n][,hostname=host]\n"
4670 " connect the user mode network stack to VLAN 'n' and send\n"
4671 " hostname 'host' to DHCP clients\n"
4674 "-net tap[,vlan=n],ifname=name\n"
4675 " connect the host TAP network interface to VLAN 'n'\n"
4677 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file]\n"
4678 " connect the host TAP network interface to VLAN 'n' and use\n"
4679 " the network script 'file' (default=%s);\n"
4680 " use 'fd=h' to connect to an already opened TAP interface\n"
4682 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
4683 " connect the vlan 'n' to another VLAN using a socket connection\n"
4684 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
4685 " connect the vlan 'n' to multicast maddr and port\n"
4686 "-net none use it alone to have zero network devices; if no -net option\n"
4687 " is provided, the default is '-net nic -net user'\n"
4690 "-tftp prefix allow tftp access to files starting with prefix [-net user]\n"
4692 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
4694 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
4695 " redirect TCP or UDP connections from host to guest [-net user]\n"
4698 "Linux boot specific:\n"
4699 "-kernel bzImage use 'bzImage' as kernel image\n"
4700 "-append cmdline use 'cmdline' as kernel command line\n"
4701 "-initrd file use 'file' as initial ram disk\n"
4703 "Debug/Expert options:\n"
4704 "-monitor dev redirect the monitor to char device 'dev'\n"
4705 "-serial dev redirect the serial port to char device 'dev'\n"
4706 "-parallel dev redirect the parallel port to char device 'dev'\n"
4707 "-pidfile file Write PID to 'file'\n"
4708 "-S freeze CPU at startup (use 'c' to start execution)\n"
4709 "-s wait gdb connection to port %d\n"
4710 "-p port change gdb connection port\n"
4711 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
4712 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
4713 " translation (t=none or lba) (usually qemu can guess them)\n"
4714 "-L path set the directory for the BIOS and VGA BIOS\n"
4716 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
4717 "-no-kqemu disable KQEMU kernel module usage\n"
4719 #ifdef USE_CODE_COPY
4720 "-no-code-copy disable code copy acceleration\n"
4723 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
4724 " (default is CL-GD5446 PCI VGA)\n"
4725 "-no-acpi disable ACPI\n"
4727 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
4728 "-vnc display start a VNC server on display\n"
4730 "During emulation, the following keys are useful:\n"
4731 "ctrl-alt-f toggle full screen\n"
4732 "ctrl-alt-n switch to virtual console 'n'\n"
4733 "ctrl-alt toggle mouse and keyboard grab\n"
4735 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4737 #ifdef CONFIG_SOFTMMU
4744 DEFAULT_NETWORK_SCRIPT,
4746 DEFAULT_GDBSTUB_PORT,
4748 #ifndef CONFIG_SOFTMMU
4750 "NOTE: this version of QEMU is faster but it needs slightly patched OSes to\n"
4751 "work. Please use the 'qemu' executable to have a more accurate (but slower)\n"
4757 #define HAS_ARG 0x0001
4771 QEMU_OPTION_snapshot,
4773 QEMU_OPTION_no_fd_bootchk,
4776 QEMU_OPTION_nographic,
4778 QEMU_OPTION_audio_help,
4779 QEMU_OPTION_soundhw,
4797 QEMU_OPTION_no_code_copy,
4799 QEMU_OPTION_localtime,
4800 QEMU_OPTION_cirrusvga,
4802 QEMU_OPTION_std_vga,
4803 QEMU_OPTION_monitor,
4805 QEMU_OPTION_parallel,
4807 QEMU_OPTION_full_screen,
4808 QEMU_OPTION_pidfile,
4809 QEMU_OPTION_no_kqemu,
4810 QEMU_OPTION_kernel_kqemu,
4811 QEMU_OPTION_win2k_hack,
4813 QEMU_OPTION_usbdevice,
4816 QEMU_OPTION_no_acpi,
4819 typedef struct QEMUOption {
4825 const QEMUOption qemu_options[] = {
4826 { "h", 0, QEMU_OPTION_h },
4828 { "M", HAS_ARG, QEMU_OPTION_M },
4829 { "fda", HAS_ARG, QEMU_OPTION_fda },
4830 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
4831 { "hda", HAS_ARG, QEMU_OPTION_hda },
4832 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
4833 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
4834 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
4835 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
4836 { "boot", HAS_ARG, QEMU_OPTION_boot },
4837 { "snapshot", 0, QEMU_OPTION_snapshot },
4839 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
4841 { "m", HAS_ARG, QEMU_OPTION_m },
4842 { "nographic", 0, QEMU_OPTION_nographic },
4843 { "k", HAS_ARG, QEMU_OPTION_k },
4845 { "audio-help", 0, QEMU_OPTION_audio_help },
4846 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
4849 { "net", HAS_ARG, QEMU_OPTION_net},
4851 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
4853 { "smb", HAS_ARG, QEMU_OPTION_smb },
4855 { "redir", HAS_ARG, QEMU_OPTION_redir },
4858 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
4859 { "append", HAS_ARG, QEMU_OPTION_append },
4860 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
4862 { "S", 0, QEMU_OPTION_S },
4863 { "s", 0, QEMU_OPTION_s },
4864 { "p", HAS_ARG, QEMU_OPTION_p },
4865 { "d", HAS_ARG, QEMU_OPTION_d },
4866 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
4867 { "L", HAS_ARG, QEMU_OPTION_L },
4868 { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
4870 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
4871 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
4873 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
4874 { "g", 1, QEMU_OPTION_g },
4876 { "localtime", 0, QEMU_OPTION_localtime },
4877 { "std-vga", 0, QEMU_OPTION_std_vga },
4878 { "monitor", 1, QEMU_OPTION_monitor },
4879 { "serial", 1, QEMU_OPTION_serial },
4880 { "parallel", 1, QEMU_OPTION_parallel },
4881 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
4882 { "full-screen", 0, QEMU_OPTION_full_screen },
4883 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
4884 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
4885 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
4886 { "smp", HAS_ARG, QEMU_OPTION_smp },
4887 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
4889 /* temporary options */
4890 { "usb", 0, QEMU_OPTION_usb },
4891 { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
4892 { "no-acpi", 0, QEMU_OPTION_no_acpi },
4896 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
4898 /* this stack is only used during signal handling */
4899 #define SIGNAL_STACK_SIZE 32768
4901 static uint8_t *signal_stack;
4905 /* password input */
4907 static BlockDriverState *get_bdrv(int index)
4909 BlockDriverState *bs;
4912 bs = bs_table[index];
4913 } else if (index < 6) {
4914 bs = fd_table[index - 4];
4921 static void read_passwords(void)
4923 BlockDriverState *bs;
4927 for(i = 0; i < 6; i++) {
4929 if (bs && bdrv_is_encrypted(bs)) {
4930 term_printf("%s is encrypted.\n", bdrv_get_device_name(bs));
4931 for(j = 0; j < 3; j++) {
4932 monitor_readline("Password: ",
4933 1, password, sizeof(password));
4934 if (bdrv_set_key(bs, password) == 0)
4936 term_printf("invalid password\n");
4942 /* XXX: currently we cannot use simultaneously different CPUs */
4943 void register_machines(void)
4945 #if defined(TARGET_I386)
4946 qemu_register_machine(&pc_machine);
4947 qemu_register_machine(&isapc_machine);
4948 #elif defined(TARGET_PPC)
4949 qemu_register_machine(&heathrow_machine);
4950 qemu_register_machine(&core99_machine);
4951 qemu_register_machine(&prep_machine);
4952 #elif defined(TARGET_MIPS)
4953 qemu_register_machine(&mips_machine);
4954 #elif defined(TARGET_SPARC)
4955 #ifdef TARGET_SPARC64
4956 qemu_register_machine(&sun4u_machine);
4958 qemu_register_machine(&sun4m_machine);
4960 #elif defined(TARGET_ARM)
4961 qemu_register_machine(&integratorcp926_machine);
4962 qemu_register_machine(&integratorcp1026_machine);
4963 qemu_register_machine(&versatilepb_machine);
4964 qemu_register_machine(&versatileab_machine);
4965 #elif defined(TARGET_SH4)
4966 qemu_register_machine(&shix_machine);
4968 #error unsupported CPU
4973 struct soundhw soundhw[] = {
4980 { .init_isa = pcspk_audio_init }
4985 "Creative Sound Blaster 16",
4988 { .init_isa = SB16_init }
4995 "Yamaha YMF262 (OPL3)",
4997 "Yamaha YM3812 (OPL2)",
5001 { .init_isa = Adlib_init }
5008 "Gravis Ultrasound GF1",
5011 { .init_isa = GUS_init }
5017 "ENSONIQ AudioPCI ES1370",
5020 { .init_pci = es1370_init }
5023 { NULL, NULL, 0, 0, { NULL } }
5026 static void select_soundhw (const char *optarg)
5030 if (*optarg == '?') {
5033 printf ("Valid sound card names (comma separated):\n");
5034 for (c = soundhw; c->name; ++c) {
5035 printf ("%-11s %s\n", c->name, c->descr);
5037 printf ("\n-soundhw all will enable all of the above\n");
5038 exit (*optarg != '?');
5046 if (!strcmp (optarg, "all")) {
5047 for (c = soundhw; c->name; ++c) {
5055 e = strchr (p, ',');
5056 l = !e ? strlen (p) : (size_t) (e - p);
5058 for (c = soundhw; c->name; ++c) {
5059 if (!strncmp (c->name, p, l)) {
5068 "Unknown sound card name (too big to show)\n");
5071 fprintf (stderr, "Unknown sound card name `%.*s'\n",
5076 p += l + (e != NULL);
5080 goto show_valid_cards;
5085 #define MAX_NET_CLIENTS 32
5087 int main(int argc, char **argv)
5089 #ifdef CONFIG_GDBSTUB
5090 int use_gdbstub, gdbstub_port;
5093 int snapshot, linux_boot;
5094 const char *initrd_filename;
5095 const char *hd_filename[MAX_DISKS], *fd_filename[MAX_FD];
5096 const char *kernel_filename, *kernel_cmdline;
5097 DisplayState *ds = &display_state;
5098 int cyls, heads, secs, translation;
5099 int start_emulation = 1;
5100 char net_clients[MAX_NET_CLIENTS][256];
5103 const char *r, *optarg;
5104 CharDriverState *monitor_hd;
5105 char monitor_device[128];
5106 char serial_devices[MAX_SERIAL_PORTS][128];
5107 int serial_device_index;
5108 char parallel_devices[MAX_PARALLEL_PORTS][128];
5109 int parallel_device_index;
5110 const char *loadvm = NULL;
5111 QEMUMachine *machine;
5112 char usb_devices[MAX_USB_CMDLINE][128];
5113 int usb_devices_index;
5115 LIST_INIT (&vm_change_state_head);
5116 #if !defined(CONFIG_SOFTMMU)
5117 /* we never want that malloc() uses mmap() */
5118 mallopt(M_MMAP_THRESHOLD, 4096 * 1024);
5120 register_machines();
5121 machine = first_machine;
5122 initrd_filename = NULL;
5123 for(i = 0; i < MAX_FD; i++)
5124 fd_filename[i] = NULL;
5125 for(i = 0; i < MAX_DISKS; i++)
5126 hd_filename[i] = NULL;
5127 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5128 vga_ram_size = VGA_RAM_SIZE;
5129 bios_size = BIOS_SIZE;
5130 #ifdef CONFIG_GDBSTUB
5132 gdbstub_port = DEFAULT_GDBSTUB_PORT;
5136 kernel_filename = NULL;
5137 kernel_cmdline = "";
5143 cyls = heads = secs = 0;
5144 translation = BIOS_ATA_TRANSLATION_AUTO;
5145 pstrcpy(monitor_device, sizeof(monitor_device), "vc");
5147 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
5148 for(i = 1; i < MAX_SERIAL_PORTS; i++)
5149 serial_devices[i][0] = '\0';
5150 serial_device_index = 0;
5152 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
5153 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
5154 parallel_devices[i][0] = '\0';
5155 parallel_device_index = 0;
5157 usb_devices_index = 0;
5162 /* default mac address of the first network interface */
5170 hd_filename[0] = argv[optind++];
5172 const QEMUOption *popt;
5175 popt = qemu_options;
5178 fprintf(stderr, "%s: invalid option -- '%s'\n",
5182 if (!strcmp(popt->name, r + 1))
5186 if (popt->flags & HAS_ARG) {
5187 if (optind >= argc) {
5188 fprintf(stderr, "%s: option '%s' requires an argument\n",
5192 optarg = argv[optind++];
5197 switch(popt->index) {
5199 machine = find_machine(optarg);
5202 printf("Supported machines are:\n");
5203 for(m = first_machine; m != NULL; m = m->next) {
5204 printf("%-10s %s%s\n",
5206 m == first_machine ? " (default)" : "");
5211 case QEMU_OPTION_initrd:
5212 initrd_filename = optarg;
5214 case QEMU_OPTION_hda:
5215 case QEMU_OPTION_hdb:
5216 case QEMU_OPTION_hdc:
5217 case QEMU_OPTION_hdd:
5220 hd_index = popt->index - QEMU_OPTION_hda;
5221 hd_filename[hd_index] = optarg;
5222 if (hd_index == cdrom_index)
5226 case QEMU_OPTION_snapshot:
5229 case QEMU_OPTION_hdachs:
5233 cyls = strtol(p, (char **)&p, 0);
5234 if (cyls < 1 || cyls > 16383)
5239 heads = strtol(p, (char **)&p, 0);
5240 if (heads < 1 || heads > 16)
5245 secs = strtol(p, (char **)&p, 0);
5246 if (secs < 1 || secs > 63)
5250 if (!strcmp(p, "none"))
5251 translation = BIOS_ATA_TRANSLATION_NONE;
5252 else if (!strcmp(p, "lba"))
5253 translation = BIOS_ATA_TRANSLATION_LBA;
5254 else if (!strcmp(p, "auto"))
5255 translation = BIOS_ATA_TRANSLATION_AUTO;
5258 } else if (*p != '\0') {
5260 fprintf(stderr, "qemu: invalid physical CHS format\n");
5265 case QEMU_OPTION_nographic:
5266 pstrcpy(monitor_device, sizeof(monitor_device), "stdio");
5267 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "stdio");
5270 case QEMU_OPTION_kernel:
5271 kernel_filename = optarg;
5273 case QEMU_OPTION_append:
5274 kernel_cmdline = optarg;
5276 case QEMU_OPTION_cdrom:
5277 if (cdrom_index >= 0) {
5278 hd_filename[cdrom_index] = optarg;
5281 case QEMU_OPTION_boot:
5282 boot_device = optarg[0];
5283 if (boot_device != 'a' &&
5286 boot_device != 'n' &&
5288 boot_device != 'c' && boot_device != 'd') {
5289 fprintf(stderr, "qemu: invalid boot device '%c'\n", boot_device);
5293 case QEMU_OPTION_fda:
5294 fd_filename[0] = optarg;
5296 case QEMU_OPTION_fdb:
5297 fd_filename[1] = optarg;
5300 case QEMU_OPTION_no_fd_bootchk:
5304 case QEMU_OPTION_no_code_copy:
5305 code_copy_enabled = 0;
5307 case QEMU_OPTION_net:
5308 if (nb_net_clients >= MAX_NET_CLIENTS) {
5309 fprintf(stderr, "qemu: too many network clients\n");
5312 pstrcpy(net_clients[nb_net_clients],
5313 sizeof(net_clients[0]),
5318 case QEMU_OPTION_tftp:
5319 tftp_prefix = optarg;
5322 case QEMU_OPTION_smb:
5323 net_slirp_smb(optarg);
5326 case QEMU_OPTION_redir:
5327 net_slirp_redir(optarg);
5331 case QEMU_OPTION_audio_help:
5335 case QEMU_OPTION_soundhw:
5336 select_soundhw (optarg);
5343 ram_size = atoi(optarg) * 1024 * 1024;
5346 if (ram_size > PHYS_RAM_MAX_SIZE) {
5347 fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
5348 PHYS_RAM_MAX_SIZE / (1024 * 1024));
5357 mask = cpu_str_to_log_mask(optarg);
5359 printf("Log items (comma separated):\n");
5360 for(item = cpu_log_items; item->mask != 0; item++) {
5361 printf("%-10s %s\n", item->name, item->help);
5368 #ifdef CONFIG_GDBSTUB
5373 gdbstub_port = atoi(optarg);
5380 start_emulation = 0;
5383 keyboard_layout = optarg;
5385 case QEMU_OPTION_localtime:
5388 case QEMU_OPTION_cirrusvga:
5389 cirrus_vga_enabled = 1;
5391 case QEMU_OPTION_std_vga:
5392 cirrus_vga_enabled = 0;
5399 w = strtol(p, (char **)&p, 10);
5402 fprintf(stderr, "qemu: invalid resolution or depth\n");
5408 h = strtol(p, (char **)&p, 10);
5413 depth = strtol(p, (char **)&p, 10);
5414 if (depth != 8 && depth != 15 && depth != 16 &&
5415 depth != 24 && depth != 32)
5417 } else if (*p == '\0') {
5418 depth = graphic_depth;
5425 graphic_depth = depth;
5428 case QEMU_OPTION_monitor:
5429 pstrcpy(monitor_device, sizeof(monitor_device), optarg);
5431 case QEMU_OPTION_serial:
5432 if (serial_device_index >= MAX_SERIAL_PORTS) {
5433 fprintf(stderr, "qemu: too many serial ports\n");
5436 pstrcpy(serial_devices[serial_device_index],
5437 sizeof(serial_devices[0]), optarg);
5438 serial_device_index++;
5440 case QEMU_OPTION_parallel:
5441 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
5442 fprintf(stderr, "qemu: too many parallel ports\n");
5445 pstrcpy(parallel_devices[parallel_device_index],
5446 sizeof(parallel_devices[0]), optarg);
5447 parallel_device_index++;
5449 case QEMU_OPTION_loadvm:
5452 case QEMU_OPTION_full_screen:
5455 case QEMU_OPTION_pidfile:
5456 create_pidfile(optarg);
5459 case QEMU_OPTION_win2k_hack:
5460 win2k_install_hack = 1;
5464 case QEMU_OPTION_no_kqemu:
5467 case QEMU_OPTION_kernel_kqemu:
5471 case QEMU_OPTION_usb:
5474 case QEMU_OPTION_usbdevice:
5476 if (usb_devices_index >= MAX_USB_CMDLINE) {
5477 fprintf(stderr, "Too many USB devices\n");
5480 pstrcpy(usb_devices[usb_devices_index],
5481 sizeof(usb_devices[usb_devices_index]),
5483 usb_devices_index++;
5485 case QEMU_OPTION_smp:
5486 smp_cpus = atoi(optarg);
5487 if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
5488 fprintf(stderr, "Invalid number of CPUs\n");
5492 case QEMU_OPTION_vnc:
5493 vnc_display = atoi(optarg);
5494 if (vnc_display < 0) {
5495 fprintf(stderr, "Invalid VNC display\n");
5499 case QEMU_OPTION_no_acpi:
5510 linux_boot = (kernel_filename != NULL);
5513 hd_filename[0] == '\0' &&
5514 (cdrom_index >= 0 && hd_filename[cdrom_index] == '\0') &&
5515 fd_filename[0] == '\0')
5518 /* boot to cd by default if no hard disk */
5519 if (hd_filename[0] == '\0' && boot_device == 'c') {
5520 if (fd_filename[0] != '\0')
5526 #if !defined(CONFIG_SOFTMMU)
5527 /* must avoid mmap() usage of glibc by setting a buffer "by hand" */
5529 static uint8_t stdout_buf[4096];
5530 setvbuf(stdout, stdout_buf, _IOLBF, sizeof(stdout_buf));
5533 setvbuf(stdout, NULL, _IOLBF, 0);
5540 /* init network clients */
5541 if (nb_net_clients == 0) {
5542 /* if no clients, we use a default config */
5543 pstrcpy(net_clients[0], sizeof(net_clients[0]),
5545 pstrcpy(net_clients[1], sizeof(net_clients[0]),
5550 for(i = 0;i < nb_net_clients; i++) {
5551 if (net_client_init(net_clients[i]) < 0)
5555 /* init the memory */
5556 phys_ram_size = ram_size + vga_ram_size + bios_size;
5558 #ifdef CONFIG_SOFTMMU
5559 phys_ram_base = qemu_vmalloc(phys_ram_size);
5560 if (!phys_ram_base) {
5561 fprintf(stderr, "Could not allocate physical memory\n");
5565 /* as we must map the same page at several addresses, we must use
5570 tmpdir = getenv("QEMU_TMPDIR");
5573 snprintf(phys_ram_file, sizeof(phys_ram_file), "%s/vlXXXXXX", tmpdir);
5574 if (mkstemp(phys_ram_file) < 0) {
5575 fprintf(stderr, "Could not create temporary memory file '%s'\n",
5579 phys_ram_fd = open(phys_ram_file, O_CREAT | O_TRUNC | O_RDWR, 0600);
5580 if (phys_ram_fd < 0) {
5581 fprintf(stderr, "Could not open temporary memory file '%s'\n",
5585 ftruncate(phys_ram_fd, phys_ram_size);
5586 unlink(phys_ram_file);
5587 phys_ram_base = mmap(get_mmap_addr(phys_ram_size),
5589 PROT_WRITE | PROT_READ, MAP_SHARED | MAP_FIXED,
5591 if (phys_ram_base == MAP_FAILED) {
5592 fprintf(stderr, "Could not map physical memory\n");
5598 /* we always create the cdrom drive, even if no disk is there */
5600 if (cdrom_index >= 0) {
5601 bs_table[cdrom_index] = bdrv_new("cdrom");
5602 bdrv_set_type_hint(bs_table[cdrom_index], BDRV_TYPE_CDROM);
5605 /* open the virtual block devices */
5606 for(i = 0; i < MAX_DISKS; i++) {
5607 if (hd_filename[i]) {
5610 snprintf(buf, sizeof(buf), "hd%c", i + 'a');
5611 bs_table[i] = bdrv_new(buf);
5613 if (bdrv_open(bs_table[i], hd_filename[i], snapshot) < 0) {
5614 fprintf(stderr, "qemu: could not open hard disk image '%s'\n",
5618 if (i == 0 && cyls != 0) {
5619 bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
5620 bdrv_set_translation_hint(bs_table[i], translation);
5625 /* we always create at least one floppy disk */
5626 fd_table[0] = bdrv_new("fda");
5627 bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
5629 for(i = 0; i < MAX_FD; i++) {
5630 if (fd_filename[i]) {
5633 snprintf(buf, sizeof(buf), "fd%c", i + 'a');
5634 fd_table[i] = bdrv_new(buf);
5635 bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
5637 if (fd_filename[i] != '\0') {
5638 if (bdrv_open(fd_table[i], fd_filename[i], snapshot) < 0) {
5639 fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
5647 register_savevm("timer", 0, 1, timer_save, timer_load, NULL);
5648 register_savevm("ram", 0, 1, ram_save, ram_load, NULL);
5651 cpu_calibrate_ticks();
5655 dumb_display_init(ds);
5656 } else if (vnc_display != -1) {
5657 vnc_display_init(ds, vnc_display);
5659 #if defined(CONFIG_SDL)
5660 sdl_display_init(ds, full_screen);
5661 #elif defined(CONFIG_COCOA)
5662 cocoa_display_init(ds, full_screen);
5664 dumb_display_init(ds);
5668 monitor_hd = qemu_chr_open(monitor_device);
5670 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
5673 monitor_init(monitor_hd, !nographic);
5675 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5676 if (serial_devices[i][0] != '\0') {
5677 serial_hds[i] = qemu_chr_open(serial_devices[i]);
5678 if (!serial_hds[i]) {
5679 fprintf(stderr, "qemu: could not open serial device '%s'\n",
5683 if (!strcmp(serial_devices[i], "vc"))
5684 qemu_chr_printf(serial_hds[i], "serial%d console\n", i);
5688 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5689 if (parallel_devices[i][0] != '\0') {
5690 parallel_hds[i] = qemu_chr_open(parallel_devices[i]);
5691 if (!parallel_hds[i]) {
5692 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
5693 parallel_devices[i]);
5696 if (!strcmp(parallel_devices[i], "vc"))
5697 qemu_chr_printf(parallel_hds[i], "parallel%d console\n", i);
5701 /* setup cpu signal handlers for MMU / self modifying code handling */
5702 #if !defined(CONFIG_SOFTMMU)
5704 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
5707 signal_stack = memalign(16, SIGNAL_STACK_SIZE);
5708 stk.ss_sp = signal_stack;
5709 stk.ss_size = SIGNAL_STACK_SIZE;
5712 if (sigaltstack(&stk, NULL) < 0) {
5713 perror("sigaltstack");
5719 struct sigaction act;
5721 sigfillset(&act.sa_mask);
5722 act.sa_flags = SA_SIGINFO;
5723 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
5724 act.sa_flags |= SA_ONSTACK;
5726 act.sa_sigaction = host_segv_handler;
5727 sigaction(SIGSEGV, &act, NULL);
5728 sigaction(SIGBUS, &act, NULL);
5729 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
5730 sigaction(SIGFPE, &act, NULL);
5737 struct sigaction act;
5738 sigfillset(&act.sa_mask);
5740 act.sa_handler = SIG_IGN;
5741 sigaction(SIGPIPE, &act, NULL);
5746 machine->init(ram_size, vga_ram_size, boot_device,
5747 ds, fd_filename, snapshot,
5748 kernel_filename, kernel_cmdline, initrd_filename);
5750 /* init USB devices */
5752 for(i = 0; i < usb_devices_index; i++) {
5753 if (usb_device_add(usb_devices[i]) < 0) {
5754 fprintf(stderr, "Warning: could not add USB device %s\n",
5760 gui_timer = qemu_new_timer(rt_clock, gui_update, NULL);
5761 qemu_mod_timer(gui_timer, qemu_get_clock(rt_clock));
5763 #ifdef CONFIG_GDBSTUB
5765 if (gdbserver_start(gdbstub_port) < 0) {
5766 fprintf(stderr, "Could not open gdbserver socket on port %d\n",
5770 printf("Waiting gdb connection on port %d\n", gdbstub_port);
5775 qemu_loadvm(loadvm);
5778 /* XXX: simplify init */
5780 if (start_emulation) {