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;
163 /***********************************************************/
164 /* x86 ISA bus support */
166 target_phys_addr_t isa_mem_base = 0;
169 uint32_t default_ioport_readb(void *opaque, uint32_t address)
171 #ifdef DEBUG_UNUSED_IOPORT
172 fprintf(stderr, "inb: port=0x%04x\n", address);
177 void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
179 #ifdef DEBUG_UNUSED_IOPORT
180 fprintf(stderr, "outb: port=0x%04x data=0x%02x\n", address, data);
184 /* default is to make two byte accesses */
185 uint32_t default_ioport_readw(void *opaque, uint32_t address)
188 data = ioport_read_table[0][address](ioport_opaque[address], address);
189 address = (address + 1) & (MAX_IOPORTS - 1);
190 data |= ioport_read_table[0][address](ioport_opaque[address], address) << 8;
194 void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
196 ioport_write_table[0][address](ioport_opaque[address], address, data & 0xff);
197 address = (address + 1) & (MAX_IOPORTS - 1);
198 ioport_write_table[0][address](ioport_opaque[address], address, (data >> 8) & 0xff);
201 uint32_t default_ioport_readl(void *opaque, uint32_t address)
203 #ifdef DEBUG_UNUSED_IOPORT
204 fprintf(stderr, "inl: port=0x%04x\n", address);
209 void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
211 #ifdef DEBUG_UNUSED_IOPORT
212 fprintf(stderr, "outl: port=0x%04x data=0x%02x\n", address, data);
216 void init_ioports(void)
220 for(i = 0; i < MAX_IOPORTS; i++) {
221 ioport_read_table[0][i] = default_ioport_readb;
222 ioport_write_table[0][i] = default_ioport_writeb;
223 ioport_read_table[1][i] = default_ioport_readw;
224 ioport_write_table[1][i] = default_ioport_writew;
225 ioport_read_table[2][i] = default_ioport_readl;
226 ioport_write_table[2][i] = default_ioport_writel;
230 /* size is the word size in byte */
231 int register_ioport_read(int start, int length, int size,
232 IOPortReadFunc *func, void *opaque)
238 } else if (size == 2) {
240 } else if (size == 4) {
243 hw_error("register_ioport_read: invalid size");
246 for(i = start; i < start + length; i += size) {
247 ioport_read_table[bsize][i] = func;
248 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
249 hw_error("register_ioport_read: invalid opaque");
250 ioport_opaque[i] = opaque;
255 /* size is the word size in byte */
256 int register_ioport_write(int start, int length, int size,
257 IOPortWriteFunc *func, void *opaque)
263 } else if (size == 2) {
265 } else if (size == 4) {
268 hw_error("register_ioport_write: invalid size");
271 for(i = start; i < start + length; i += size) {
272 ioport_write_table[bsize][i] = func;
273 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
274 hw_error("register_ioport_read: invalid opaque");
275 ioport_opaque[i] = opaque;
280 void isa_unassign_ioport(int start, int length)
284 for(i = start; i < start + length; i++) {
285 ioport_read_table[0][i] = default_ioport_readb;
286 ioport_read_table[1][i] = default_ioport_readw;
287 ioport_read_table[2][i] = default_ioport_readl;
289 ioport_write_table[0][i] = default_ioport_writeb;
290 ioport_write_table[1][i] = default_ioport_writew;
291 ioport_write_table[2][i] = default_ioport_writel;
295 /***********************************************************/
297 void pstrcpy(char *buf, int buf_size, const char *str)
307 if (c == 0 || q >= buf + buf_size - 1)
314 /* strcat and truncate. */
315 char *pstrcat(char *buf, int buf_size, const char *s)
320 pstrcpy(buf + len, buf_size - len, s);
324 int strstart(const char *str, const char *val, const char **ptr)
340 void cpu_outb(CPUState *env, int addr, int val)
343 if (loglevel & CPU_LOG_IOPORT)
344 fprintf(logfile, "outb: %04x %02x\n", addr, val);
346 ioport_write_table[0][addr](ioport_opaque[addr], addr, val);
349 env->last_io_time = cpu_get_time_fast();
353 void cpu_outw(CPUState *env, int addr, int val)
356 if (loglevel & CPU_LOG_IOPORT)
357 fprintf(logfile, "outw: %04x %04x\n", addr, val);
359 ioport_write_table[1][addr](ioport_opaque[addr], addr, val);
362 env->last_io_time = cpu_get_time_fast();
366 void cpu_outl(CPUState *env, int addr, int val)
369 if (loglevel & CPU_LOG_IOPORT)
370 fprintf(logfile, "outl: %04x %08x\n", addr, val);
372 ioport_write_table[2][addr](ioport_opaque[addr], addr, val);
375 env->last_io_time = cpu_get_time_fast();
379 int cpu_inb(CPUState *env, int addr)
382 val = ioport_read_table[0][addr](ioport_opaque[addr], addr);
384 if (loglevel & CPU_LOG_IOPORT)
385 fprintf(logfile, "inb : %04x %02x\n", addr, val);
389 env->last_io_time = cpu_get_time_fast();
394 int cpu_inw(CPUState *env, int addr)
397 val = ioport_read_table[1][addr](ioport_opaque[addr], addr);
399 if (loglevel & CPU_LOG_IOPORT)
400 fprintf(logfile, "inw : %04x %04x\n", addr, val);
404 env->last_io_time = cpu_get_time_fast();
409 int cpu_inl(CPUState *env, int addr)
412 val = ioport_read_table[2][addr](ioport_opaque[addr], addr);
414 if (loglevel & CPU_LOG_IOPORT)
415 fprintf(logfile, "inl : %04x %08x\n", addr, val);
419 env->last_io_time = cpu_get_time_fast();
424 /***********************************************************/
425 void hw_error(const char *fmt, ...)
431 fprintf(stderr, "qemu: hardware error: ");
432 vfprintf(stderr, fmt, ap);
433 fprintf(stderr, "\n");
434 for(env = first_cpu; env != NULL; env = env->next_cpu) {
435 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
437 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
439 cpu_dump_state(env, stderr, fprintf, 0);
446 /***********************************************************/
449 static QEMUPutKBDEvent *qemu_put_kbd_event;
450 static void *qemu_put_kbd_event_opaque;
451 static QEMUPutMouseEvent *qemu_put_mouse_event;
452 static void *qemu_put_mouse_event_opaque;
453 static int qemu_put_mouse_event_absolute;
455 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
457 qemu_put_kbd_event_opaque = opaque;
458 qemu_put_kbd_event = func;
461 void qemu_add_mouse_event_handler(QEMUPutMouseEvent *func, void *opaque, int absolute)
463 qemu_put_mouse_event_opaque = opaque;
464 qemu_put_mouse_event = func;
465 qemu_put_mouse_event_absolute = absolute;
468 void kbd_put_keycode(int keycode)
470 if (qemu_put_kbd_event) {
471 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
475 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
477 if (qemu_put_mouse_event) {
478 qemu_put_mouse_event(qemu_put_mouse_event_opaque,
479 dx, dy, dz, buttons_state);
483 int kbd_mouse_is_absolute(void)
485 return qemu_put_mouse_event_absolute;
488 /***********************************************************/
491 #if defined(__powerpc__)
493 static inline uint32_t get_tbl(void)
496 asm volatile("mftb %0" : "=r" (tbl));
500 static inline uint32_t get_tbu(void)
503 asm volatile("mftbu %0" : "=r" (tbl));
507 int64_t cpu_get_real_ticks(void)
510 /* NOTE: we test if wrapping has occurred */
516 return ((int64_t)h << 32) | l;
519 #elif defined(__i386__)
521 int64_t cpu_get_real_ticks(void)
525 QueryPerformanceCounter(&ti);
529 asm volatile ("rdtsc" : "=A" (val));
534 #elif defined(__x86_64__)
536 int64_t cpu_get_real_ticks(void)
540 asm volatile("rdtsc" : "=a" (low), "=d" (high));
547 #elif defined(__ia64)
549 int64_t cpu_get_real_ticks(void)
552 asm volatile ("mov %0 = ar.itc" : "=r"(val) :: "memory");
556 #elif defined(__s390__)
558 int64_t cpu_get_real_ticks(void)
561 asm volatile("stck 0(%1)" : "=m" (val) : "a" (&val) : "cc");
566 #error unsupported CPU
569 static int64_t cpu_ticks_prev;
570 static int64_t cpu_ticks_offset;
571 static int cpu_ticks_enabled;
573 static inline int64_t cpu_get_ticks(void)
575 if (!cpu_ticks_enabled) {
576 return cpu_ticks_offset;
579 ticks = cpu_get_real_ticks();
580 if (cpu_ticks_prev > ticks) {
581 /* Note: non increasing ticks may happen if the host uses
583 cpu_ticks_offset += cpu_ticks_prev - ticks;
585 cpu_ticks_prev = ticks;
586 return ticks + cpu_ticks_offset;
590 /* enable cpu_get_ticks() */
591 void cpu_enable_ticks(void)
593 if (!cpu_ticks_enabled) {
594 cpu_ticks_offset -= cpu_get_real_ticks();
595 cpu_ticks_enabled = 1;
599 /* disable cpu_get_ticks() : the clock is stopped. You must not call
600 cpu_get_ticks() after that. */
601 void cpu_disable_ticks(void)
603 if (cpu_ticks_enabled) {
604 cpu_ticks_offset = cpu_get_ticks();
605 cpu_ticks_enabled = 0;
610 void cpu_calibrate_ticks(void)
615 ret = QueryPerformanceFrequency(&freq);
617 fprintf(stderr, "Could not calibrate ticks\n");
620 ticks_per_sec = freq.QuadPart;
624 static int64_t get_clock(void)
627 gettimeofday(&tv, NULL);
628 return tv.tv_sec * 1000000LL + tv.tv_usec;
631 void cpu_calibrate_ticks(void)
636 ticks = cpu_get_real_ticks();
638 usec = get_clock() - usec;
639 ticks = cpu_get_real_ticks() - ticks;
640 ticks_per_sec = (ticks * 1000000LL + (usec >> 1)) / usec;
644 /* compute with 96 bit intermediate result: (a*b)/c */
645 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
650 #ifdef WORDS_BIGENDIAN
660 rl = (uint64_t)u.l.low * (uint64_t)b;
661 rh = (uint64_t)u.l.high * (uint64_t)b;
664 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
668 #define QEMU_TIMER_REALTIME 0
669 #define QEMU_TIMER_VIRTUAL 1
673 /* XXX: add frequency */
681 struct QEMUTimer *next;
687 static QEMUTimer *active_timers[2];
689 static MMRESULT timerID;
690 static HANDLE host_alarm = NULL;
691 static unsigned int period = 1;
693 /* frequency of the times() clock tick */
694 static int timer_freq;
697 QEMUClock *qemu_new_clock(int type)
700 clock = qemu_mallocz(sizeof(QEMUClock));
707 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
711 ts = qemu_mallocz(sizeof(QEMUTimer));
718 void qemu_free_timer(QEMUTimer *ts)
723 /* stop a timer, but do not dealloc it */
724 void qemu_del_timer(QEMUTimer *ts)
728 /* NOTE: this code must be signal safe because
729 qemu_timer_expired() can be called from a signal. */
730 pt = &active_timers[ts->clock->type];
743 /* modify the current timer so that it will be fired when current_time
744 >= expire_time. The corresponding callback will be called. */
745 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
751 /* add the timer in the sorted list */
752 /* NOTE: this code must be signal safe because
753 qemu_timer_expired() can be called from a signal. */
754 pt = &active_timers[ts->clock->type];
759 if (t->expire_time > expire_time)
763 ts->expire_time = expire_time;
768 int qemu_timer_pending(QEMUTimer *ts)
771 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
778 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
782 return (timer_head->expire_time <= current_time);
785 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
791 if (!ts || ts->expire_time > current_time)
793 /* remove timer from the list before calling the callback */
794 *ptimer_head = ts->next;
797 /* run the callback (the timer list can be modified) */
802 int64_t qemu_get_clock(QEMUClock *clock)
804 switch(clock->type) {
805 case QEMU_TIMER_REALTIME:
807 return GetTickCount();
812 /* Note that using gettimeofday() is not a good solution
813 for timers because its value change when the date is
815 if (timer_freq == 100) {
816 return times(&tp) * 10;
818 return ((int64_t)times(&tp) * 1000) / timer_freq;
823 case QEMU_TIMER_VIRTUAL:
824 return cpu_get_ticks();
829 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
831 uint64_t expire_time;
833 if (qemu_timer_pending(ts)) {
834 expire_time = ts->expire_time;
838 qemu_put_be64(f, expire_time);
841 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
843 uint64_t expire_time;
845 expire_time = qemu_get_be64(f);
846 if (expire_time != -1) {
847 qemu_mod_timer(ts, expire_time);
853 static void timer_save(QEMUFile *f, void *opaque)
855 if (cpu_ticks_enabled) {
856 hw_error("cannot save state if virtual timers are running");
858 qemu_put_be64s(f, &cpu_ticks_offset);
859 qemu_put_be64s(f, &ticks_per_sec);
862 static int timer_load(QEMUFile *f, void *opaque, int version_id)
866 if (cpu_ticks_enabled) {
869 qemu_get_be64s(f, &cpu_ticks_offset);
870 qemu_get_be64s(f, &ticks_per_sec);
875 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
876 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
878 static void host_alarm_handler(int host_signum)
882 #define DISP_FREQ 1000
884 static int64_t delta_min = INT64_MAX;
885 static int64_t delta_max, delta_cum, last_clock, delta, ti;
887 ti = qemu_get_clock(vm_clock);
888 if (last_clock != 0) {
889 delta = ti - last_clock;
890 if (delta < delta_min)
892 if (delta > delta_max)
895 if (++count == DISP_FREQ) {
896 printf("timer: min=%lld us max=%lld us avg=%lld us avg_freq=%0.3f Hz\n",
897 muldiv64(delta_min, 1000000, ticks_per_sec),
898 muldiv64(delta_max, 1000000, ticks_per_sec),
899 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
900 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
902 delta_min = INT64_MAX;
910 if (qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
911 qemu_get_clock(vm_clock)) ||
912 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
913 qemu_get_clock(rt_clock))) {
915 SetEvent(host_alarm);
917 CPUState *env = cpu_single_env;
919 /* stop the currently executing cpu because a timer occured */
920 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
922 if (env->kqemu_enabled) {
923 kqemu_cpu_interrupt(env);
932 #if defined(__linux__)
934 #define RTC_FREQ 1024
938 static int start_rtc_timer(void)
940 rtc_fd = open("/dev/rtc", O_RDONLY);
943 if (ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
944 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
945 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
946 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
949 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
954 pit_min_timer_count = PIT_FREQ / RTC_FREQ;
960 static int start_rtc_timer(void)
965 #endif /* !defined(__linux__) */
967 #endif /* !defined(_WIN32) */
969 static void init_timers(void)
971 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
972 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
979 ZeroMemory(&tc, sizeof(TIMECAPS));
980 timeGetDevCaps(&tc, sizeof(TIMECAPS));
981 if (period < tc.wPeriodMin)
982 period = tc.wPeriodMin;
983 timeBeginPeriod(period);
984 timerID = timeSetEvent(1, // interval (ms)
985 period, // resolution
986 host_alarm_handler, // function
987 (DWORD)&count, // user parameter
988 TIME_PERIODIC | TIME_CALLBACK_FUNCTION);
990 perror("failed timer alarm");
993 host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
995 perror("failed CreateEvent");
998 ResetEvent(host_alarm);
1000 pit_min_timer_count = ((uint64_t)10000 * PIT_FREQ) / 1000000;
1003 struct sigaction act;
1004 struct itimerval itv;
1006 /* get times() syscall frequency */
1007 timer_freq = sysconf(_SC_CLK_TCK);
1010 sigfillset(&act.sa_mask);
1012 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
1013 act.sa_flags |= SA_ONSTACK;
1015 act.sa_handler = host_alarm_handler;
1016 sigaction(SIGALRM, &act, NULL);
1018 itv.it_interval.tv_sec = 0;
1019 itv.it_interval.tv_usec = 999; /* for i386 kernel 2.6 to get 1 ms */
1020 itv.it_value.tv_sec = 0;
1021 itv.it_value.tv_usec = 10 * 1000;
1022 setitimer(ITIMER_REAL, &itv, NULL);
1023 /* we probe the tick duration of the kernel to inform the user if
1024 the emulated kernel requested a too high timer frequency */
1025 getitimer(ITIMER_REAL, &itv);
1027 #if defined(__linux__)
1028 /* XXX: force /dev/rtc usage because even 2.6 kernels may not
1029 have timers with 1 ms resolution. The correct solution will
1030 be to use the POSIX real time timers available in recent
1032 if (itv.it_interval.tv_usec > 1000 || 1) {
1033 /* try to use /dev/rtc to have a faster timer */
1034 if (start_rtc_timer() < 0)
1036 /* disable itimer */
1037 itv.it_interval.tv_sec = 0;
1038 itv.it_interval.tv_usec = 0;
1039 itv.it_value.tv_sec = 0;
1040 itv.it_value.tv_usec = 0;
1041 setitimer(ITIMER_REAL, &itv, NULL);
1044 sigaction(SIGIO, &act, NULL);
1045 fcntl(rtc_fd, F_SETFL, O_ASYNC);
1046 fcntl(rtc_fd, F_SETOWN, getpid());
1048 #endif /* defined(__linux__) */
1051 pit_min_timer_count = ((uint64_t)itv.it_interval.tv_usec *
1052 PIT_FREQ) / 1000000;
1058 void quit_timers(void)
1061 timeKillEvent(timerID);
1062 timeEndPeriod(period);
1064 CloseHandle(host_alarm);
1070 /***********************************************************/
1071 /* character device */
1073 int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1075 return s->chr_write(s, buf, len);
1078 int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1082 return s->chr_ioctl(s, cmd, arg);
1085 void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1090 vsnprintf(buf, sizeof(buf), fmt, ap);
1091 qemu_chr_write(s, buf, strlen(buf));
1095 void qemu_chr_send_event(CharDriverState *s, int event)
1097 if (s->chr_send_event)
1098 s->chr_send_event(s, event);
1101 void qemu_chr_add_read_handler(CharDriverState *s,
1102 IOCanRWHandler *fd_can_read,
1103 IOReadHandler *fd_read, void *opaque)
1105 s->chr_add_read_handler(s, fd_can_read, fd_read, opaque);
1108 void qemu_chr_add_event_handler(CharDriverState *s, IOEventHandler *chr_event)
1110 s->chr_event = chr_event;
1113 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1118 static void null_chr_add_read_handler(CharDriverState *chr,
1119 IOCanRWHandler *fd_can_read,
1120 IOReadHandler *fd_read, void *opaque)
1124 CharDriverState *qemu_chr_open_null(void)
1126 CharDriverState *chr;
1128 chr = qemu_mallocz(sizeof(CharDriverState));
1131 chr->chr_write = null_chr_write;
1132 chr->chr_add_read_handler = null_chr_add_read_handler;
1138 static void socket_cleanup(void)
1143 static int socket_init(void)
1148 ret = WSAStartup(MAKEWORD(2,2), &Data);
1150 err = WSAGetLastError();
1151 fprintf(stderr, "WSAStartup: %d\n", err);
1154 atexit(socket_cleanup);
1158 static int send_all(int fd, const uint8_t *buf, int len1)
1164 ret = send(fd, buf, len, 0);
1167 errno = WSAGetLastError();
1168 if (errno != WSAEWOULDBLOCK) {
1171 } else if (ret == 0) {
1181 void socket_set_nonblock(int fd)
1183 unsigned long opt = 1;
1184 ioctlsocket(fd, FIONBIO, &opt);
1189 static int unix_write(int fd, const uint8_t *buf, int len1)
1195 ret = write(fd, buf, len);
1197 if (errno != EINTR && errno != EAGAIN)
1199 } else if (ret == 0) {
1209 static inline int send_all(int fd, const uint8_t *buf, int len1)
1211 return unix_write(fd, buf, len1);
1214 void socket_set_nonblock(int fd)
1216 fcntl(fd, F_SETFL, O_NONBLOCK);
1218 #endif /* !_WIN32 */
1224 IOCanRWHandler *fd_can_read;
1225 IOReadHandler *fd_read;
1230 #define STDIO_MAX_CLIENTS 2
1232 static int stdio_nb_clients;
1233 static CharDriverState *stdio_clients[STDIO_MAX_CLIENTS];
1235 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1237 FDCharDriver *s = chr->opaque;
1238 return unix_write(s->fd_out, buf, len);
1241 static int fd_chr_read_poll(void *opaque)
1243 CharDriverState *chr = opaque;
1244 FDCharDriver *s = chr->opaque;
1246 s->max_size = s->fd_can_read(s->fd_opaque);
1250 static void fd_chr_read(void *opaque)
1252 CharDriverState *chr = opaque;
1253 FDCharDriver *s = chr->opaque;
1258 if (len > s->max_size)
1262 size = read(s->fd_in, buf, len);
1264 s->fd_read(s->fd_opaque, buf, size);
1268 static void fd_chr_add_read_handler(CharDriverState *chr,
1269 IOCanRWHandler *fd_can_read,
1270 IOReadHandler *fd_read, void *opaque)
1272 FDCharDriver *s = chr->opaque;
1274 if (s->fd_in >= 0) {
1275 s->fd_can_read = fd_can_read;
1276 s->fd_read = fd_read;
1277 s->fd_opaque = opaque;
1278 if (nographic && s->fd_in == 0) {
1280 qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
1281 fd_chr_read, NULL, chr);
1286 /* open a character device to a unix fd */
1287 CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
1289 CharDriverState *chr;
1292 chr = qemu_mallocz(sizeof(CharDriverState));
1295 s = qemu_mallocz(sizeof(FDCharDriver));
1303 chr->chr_write = fd_chr_write;
1304 chr->chr_add_read_handler = fd_chr_add_read_handler;
1308 CharDriverState *qemu_chr_open_file_out(const char *file_out)
1312 fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666);
1315 return qemu_chr_open_fd(-1, fd_out);
1318 CharDriverState *qemu_chr_open_pipe(const char *filename)
1322 fd = open(filename, O_RDWR | O_BINARY);
1325 return qemu_chr_open_fd(fd, fd);
1329 /* for STDIO, we handle the case where several clients use it
1332 #define TERM_ESCAPE 0x01 /* ctrl-a is used for escape */
1334 #define TERM_FIFO_MAX_SIZE 1
1336 static int term_got_escape, client_index;
1337 static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
1340 void term_print_help(void)
1343 "C-a h print this help\n"
1344 "C-a x exit emulator\n"
1345 "C-a s save disk data back to file (if -snapshot)\n"
1346 "C-a b send break (magic sysrq)\n"
1347 "C-a c switch between console and monitor\n"
1348 "C-a C-a send C-a\n"
1352 /* called when a char is received */
1353 static void stdio_received_byte(int ch)
1355 if (term_got_escape) {
1356 term_got_escape = 0;
1367 for (i = 0; i < MAX_DISKS; i++) {
1369 bdrv_commit(bs_table[i]);
1374 if (client_index < stdio_nb_clients) {
1375 CharDriverState *chr;
1378 chr = stdio_clients[client_index];
1380 chr->chr_event(s->fd_opaque, CHR_EVENT_BREAK);
1385 if (client_index >= stdio_nb_clients)
1387 if (client_index == 0) {
1388 /* send a new line in the monitor to get the prompt */
1396 } else if (ch == TERM_ESCAPE) {
1397 term_got_escape = 1;
1400 if (client_index < stdio_nb_clients) {
1402 CharDriverState *chr;
1405 chr = stdio_clients[client_index];
1407 if (s->fd_can_read(s->fd_opaque) > 0) {
1409 s->fd_read(s->fd_opaque, buf, 1);
1410 } else if (term_fifo_size == 0) {
1411 term_fifo[term_fifo_size++] = ch;
1417 static int stdio_read_poll(void *opaque)
1419 CharDriverState *chr;
1422 if (client_index < stdio_nb_clients) {
1423 chr = stdio_clients[client_index];
1425 /* try to flush the queue if needed */
1426 if (term_fifo_size != 0 && s->fd_can_read(s->fd_opaque) > 0) {
1427 s->fd_read(s->fd_opaque, term_fifo, 1);
1430 /* see if we can absorb more chars */
1431 if (term_fifo_size == 0)
1440 static void stdio_read(void *opaque)
1445 size = read(0, buf, 1);
1447 stdio_received_byte(buf[0]);
1450 /* init terminal so that we can grab keys */
1451 static struct termios oldtty;
1452 static int old_fd0_flags;
1454 static void term_exit(void)
1456 tcsetattr (0, TCSANOW, &oldtty);
1457 fcntl(0, F_SETFL, old_fd0_flags);
1460 static void term_init(void)
1464 tcgetattr (0, &tty);
1466 old_fd0_flags = fcntl(0, F_GETFL);
1468 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1469 |INLCR|IGNCR|ICRNL|IXON);
1470 tty.c_oflag |= OPOST;
1471 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1472 /* if graphical mode, we allow Ctrl-C handling */
1474 tty.c_lflag &= ~ISIG;
1475 tty.c_cflag &= ~(CSIZE|PARENB);
1478 tty.c_cc[VTIME] = 0;
1480 tcsetattr (0, TCSANOW, &tty);
1484 fcntl(0, F_SETFL, O_NONBLOCK);
1487 CharDriverState *qemu_chr_open_stdio(void)
1489 CharDriverState *chr;
1492 if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
1494 chr = qemu_chr_open_fd(0, 1);
1495 if (stdio_nb_clients == 0)
1496 qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, NULL);
1497 client_index = stdio_nb_clients;
1499 if (stdio_nb_clients != 0)
1501 chr = qemu_chr_open_fd(0, 1);
1503 stdio_clients[stdio_nb_clients++] = chr;
1504 if (stdio_nb_clients == 1) {
1505 /* set the terminal in raw mode */
1511 #if defined(__linux__)
1512 CharDriverState *qemu_chr_open_pty(void)
1515 char slave_name[1024];
1516 int master_fd, slave_fd;
1518 /* Not satisfying */
1519 if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
1523 /* Disabling local echo and line-buffered output */
1524 tcgetattr (master_fd, &tty);
1525 tty.c_lflag &= ~(ECHO|ICANON|ISIG);
1527 tty.c_cc[VTIME] = 0;
1528 tcsetattr (master_fd, TCSAFLUSH, &tty);
1530 fprintf(stderr, "char device redirected to %s\n", slave_name);
1531 return qemu_chr_open_fd(master_fd, master_fd);
1534 static void tty_serial_init(int fd, int speed,
1535 int parity, int data_bits, int stop_bits)
1541 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1542 speed, parity, data_bits, stop_bits);
1544 tcgetattr (fd, &tty);
1586 cfsetispeed(&tty, spd);
1587 cfsetospeed(&tty, spd);
1589 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1590 |INLCR|IGNCR|ICRNL|IXON);
1591 tty.c_oflag |= OPOST;
1592 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1593 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS);
1614 tty.c_cflag |= PARENB;
1617 tty.c_cflag |= PARENB | PARODD;
1621 tcsetattr (fd, TCSANOW, &tty);
1624 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1626 FDCharDriver *s = chr->opaque;
1629 case CHR_IOCTL_SERIAL_SET_PARAMS:
1631 QEMUSerialSetParams *ssp = arg;
1632 tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
1633 ssp->data_bits, ssp->stop_bits);
1636 case CHR_IOCTL_SERIAL_SET_BREAK:
1638 int enable = *(int *)arg;
1640 tcsendbreak(s->fd_in, 1);
1649 CharDriverState *qemu_chr_open_tty(const char *filename)
1651 CharDriverState *chr;
1654 fd = open(filename, O_RDWR | O_NONBLOCK);
1657 fcntl(fd, F_SETFL, O_NONBLOCK);
1658 tty_serial_init(fd, 115200, 'N', 8, 1);
1659 chr = qemu_chr_open_fd(fd, fd);
1662 chr->chr_ioctl = tty_serial_ioctl;
1666 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1668 int fd = (int)chr->opaque;
1672 case CHR_IOCTL_PP_READ_DATA:
1673 if (ioctl(fd, PPRDATA, &b) < 0)
1675 *(uint8_t *)arg = b;
1677 case CHR_IOCTL_PP_WRITE_DATA:
1678 b = *(uint8_t *)arg;
1679 if (ioctl(fd, PPWDATA, &b) < 0)
1682 case CHR_IOCTL_PP_READ_CONTROL:
1683 if (ioctl(fd, PPRCONTROL, &b) < 0)
1685 *(uint8_t *)arg = b;
1687 case CHR_IOCTL_PP_WRITE_CONTROL:
1688 b = *(uint8_t *)arg;
1689 if (ioctl(fd, PPWCONTROL, &b) < 0)
1692 case CHR_IOCTL_PP_READ_STATUS:
1693 if (ioctl(fd, PPRSTATUS, &b) < 0)
1695 *(uint8_t *)arg = b;
1703 CharDriverState *qemu_chr_open_pp(const char *filename)
1705 CharDriverState *chr;
1708 fd = open(filename, O_RDWR);
1712 if (ioctl(fd, PPCLAIM) < 0) {
1717 chr = qemu_mallocz(sizeof(CharDriverState));
1722 chr->opaque = (void *)fd;
1723 chr->chr_write = null_chr_write;
1724 chr->chr_add_read_handler = null_chr_add_read_handler;
1725 chr->chr_ioctl = pp_ioctl;
1730 CharDriverState *qemu_chr_open_pty(void)
1736 #endif /* !defined(_WIN32) */
1740 IOCanRWHandler *fd_can_read;
1741 IOReadHandler *fd_read;
1744 HANDLE hcom, hrecv, hsend;
1745 OVERLAPPED orecv, osend;
1750 #define NSENDBUF 2048
1751 #define NRECVBUF 2048
1752 #define MAXCONNECT 1
1753 #define NTIMEOUT 5000
1755 static int win_chr_poll(void *opaque);
1756 static int win_chr_pipe_poll(void *opaque);
1758 static void win_chr_close2(WinCharState *s)
1761 CloseHandle(s->hsend);
1765 CloseHandle(s->hrecv);
1769 CloseHandle(s->hcom);
1773 qemu_del_polling_cb(win_chr_pipe_poll, s);
1775 qemu_del_polling_cb(win_chr_poll, s);
1778 static void win_chr_close(CharDriverState *chr)
1780 WinCharState *s = chr->opaque;
1784 static int win_chr_init(WinCharState *s, const char *filename)
1787 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
1792 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1794 fprintf(stderr, "Failed CreateEvent\n");
1797 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1799 fprintf(stderr, "Failed CreateEvent\n");
1803 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
1804 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
1805 if (s->hcom == INVALID_HANDLE_VALUE) {
1806 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
1811 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
1812 fprintf(stderr, "Failed SetupComm\n");
1816 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
1817 size = sizeof(COMMCONFIG);
1818 GetDefaultCommConfig(filename, &comcfg, &size);
1819 comcfg.dcb.DCBlength = sizeof(DCB);
1820 CommConfigDialog(filename, NULL, &comcfg);
1822 if (!SetCommState(s->hcom, &comcfg.dcb)) {
1823 fprintf(stderr, "Failed SetCommState\n");
1827 if (!SetCommMask(s->hcom, EV_ERR)) {
1828 fprintf(stderr, "Failed SetCommMask\n");
1832 cto.ReadIntervalTimeout = MAXDWORD;
1833 if (!SetCommTimeouts(s->hcom, &cto)) {
1834 fprintf(stderr, "Failed SetCommTimeouts\n");
1838 if (!ClearCommError(s->hcom, &err, &comstat)) {
1839 fprintf(stderr, "Failed ClearCommError\n");
1842 qemu_add_polling_cb(win_chr_poll, s);
1850 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
1852 WinCharState *s = chr->opaque;
1853 DWORD len, ret, size, err;
1856 ZeroMemory(&s->osend, sizeof(s->osend));
1857 s->osend.hEvent = s->hsend;
1860 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
1862 ret = WriteFile(s->hcom, buf, len, &size, NULL);
1864 err = GetLastError();
1865 if (err == ERROR_IO_PENDING) {
1866 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
1884 static int win_chr_read_poll(WinCharState *s)
1886 s->max_size = s->fd_can_read(s->win_opaque);
1890 static void win_chr_readfile(WinCharState *s)
1896 ZeroMemory(&s->orecv, sizeof(s->orecv));
1897 s->orecv.hEvent = s->hrecv;
1898 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
1900 err = GetLastError();
1901 if (err == ERROR_IO_PENDING) {
1902 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
1907 s->fd_read(s->win_opaque, buf, size);
1911 static void win_chr_read(WinCharState *s)
1913 if (s->len > s->max_size)
1914 s->len = s->max_size;
1918 win_chr_readfile(s);
1921 static int win_chr_poll(void *opaque)
1923 WinCharState *s = opaque;
1927 ClearCommError(s->hcom, &comerr, &status);
1928 if (status.cbInQue > 0) {
1929 s->len = status.cbInQue;
1930 win_chr_read_poll(s);
1937 static void win_chr_add_read_handler(CharDriverState *chr,
1938 IOCanRWHandler *fd_can_read,
1939 IOReadHandler *fd_read, void *opaque)
1941 WinCharState *s = chr->opaque;
1943 s->fd_can_read = fd_can_read;
1944 s->fd_read = fd_read;
1945 s->win_opaque = opaque;
1948 CharDriverState *qemu_chr_open_win(const char *filename)
1950 CharDriverState *chr;
1953 chr = qemu_mallocz(sizeof(CharDriverState));
1956 s = qemu_mallocz(sizeof(WinCharState));
1962 chr->chr_write = win_chr_write;
1963 chr->chr_add_read_handler = win_chr_add_read_handler;
1964 chr->chr_close = win_chr_close;
1966 if (win_chr_init(s, filename) < 0) {
1974 static int win_chr_pipe_poll(void *opaque)
1976 WinCharState *s = opaque;
1979 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
1982 win_chr_read_poll(s);
1989 static int win_chr_pipe_init(WinCharState *s, const char *filename)
1998 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2000 fprintf(stderr, "Failed CreateEvent\n");
2003 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2005 fprintf(stderr, "Failed CreateEvent\n");
2009 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
2010 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2011 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
2013 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2014 if (s->hcom == INVALID_HANDLE_VALUE) {
2015 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
2020 ZeroMemory(&ov, sizeof(ov));
2021 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2022 ret = ConnectNamedPipe(s->hcom, &ov);
2024 fprintf(stderr, "Failed ConnectNamedPipe\n");
2028 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2030 fprintf(stderr, "Failed GetOverlappedResult\n");
2032 CloseHandle(ov.hEvent);
2039 CloseHandle(ov.hEvent);
2042 qemu_add_polling_cb(win_chr_pipe_poll, s);
2051 CharDriverState *qemu_chr_open_win_pipe(const char *filename)
2053 CharDriverState *chr;
2056 chr = qemu_mallocz(sizeof(CharDriverState));
2059 s = qemu_mallocz(sizeof(WinCharState));
2065 chr->chr_write = win_chr_write;
2066 chr->chr_add_read_handler = win_chr_add_read_handler;
2067 chr->chr_close = win_chr_close;
2069 if (win_chr_pipe_init(s, filename) < 0) {
2077 CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
2079 CharDriverState *chr;
2082 chr = qemu_mallocz(sizeof(CharDriverState));
2085 s = qemu_mallocz(sizeof(WinCharState));
2092 chr->chr_write = win_chr_write;
2093 chr->chr_add_read_handler = win_chr_add_read_handler;
2097 CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
2101 fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
2102 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2103 if (fd_out == INVALID_HANDLE_VALUE)
2106 return qemu_chr_open_win_file(fd_out);
2110 CharDriverState *qemu_chr_open(const char *filename)
2114 if (!strcmp(filename, "vc")) {
2115 return text_console_init(&display_state);
2116 } else if (!strcmp(filename, "null")) {
2117 return qemu_chr_open_null();
2120 if (strstart(filename, "file:", &p)) {
2121 return qemu_chr_open_file_out(p);
2122 } else if (strstart(filename, "pipe:", &p)) {
2123 return qemu_chr_open_pipe(p);
2124 } else if (!strcmp(filename, "pty")) {
2125 return qemu_chr_open_pty();
2126 } else if (!strcmp(filename, "stdio")) {
2127 return qemu_chr_open_stdio();
2130 #if defined(__linux__)
2131 if (strstart(filename, "/dev/parport", NULL)) {
2132 return qemu_chr_open_pp(filename);
2134 if (strstart(filename, "/dev/", NULL)) {
2135 return qemu_chr_open_tty(filename);
2139 if (strstart(filename, "COM", NULL)) {
2140 return qemu_chr_open_win(filename);
2142 if (strstart(filename, "pipe:", &p)) {
2143 return qemu_chr_open_win_pipe(p);
2145 if (strstart(filename, "file:", &p)) {
2146 return qemu_chr_open_win_file_out(p);
2154 void qemu_chr_close(CharDriverState *chr)
2157 chr->chr_close(chr);
2160 /***********************************************************/
2161 /* network device redirectors */
2163 void hex_dump(FILE *f, const uint8_t *buf, int size)
2167 for(i=0;i<size;i+=16) {
2171 fprintf(f, "%08x ", i);
2174 fprintf(f, " %02x", buf[i+j]);
2179 for(j=0;j<len;j++) {
2181 if (c < ' ' || c > '~')
2183 fprintf(f, "%c", c);
2189 static int parse_macaddr(uint8_t *macaddr, const char *p)
2192 for(i = 0; i < 6; i++) {
2193 macaddr[i] = strtol(p, (char **)&p, 16);
2206 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
2211 p1 = strchr(p, sep);
2217 if (len > buf_size - 1)
2219 memcpy(buf, p, len);
2226 int parse_host_port(struct sockaddr_in *saddr, const char *str)
2234 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2236 saddr->sin_family = AF_INET;
2237 if (buf[0] == '\0') {
2238 saddr->sin_addr.s_addr = 0;
2240 if (isdigit(buf[0])) {
2241 if (!inet_aton(buf, &saddr->sin_addr))
2244 if ((he = gethostbyname(buf)) == NULL)
2246 saddr->sin_addr = *(struct in_addr *)he->h_addr;
2249 port = strtol(p, (char **)&r, 0);
2252 saddr->sin_port = htons(port);
2256 /* find or alloc a new VLAN */
2257 VLANState *qemu_find_vlan(int id)
2259 VLANState **pvlan, *vlan;
2260 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
2264 vlan = qemu_mallocz(sizeof(VLANState));
2269 pvlan = &first_vlan;
2270 while (*pvlan != NULL)
2271 pvlan = &(*pvlan)->next;
2276 VLANClientState *qemu_new_vlan_client(VLANState *vlan,
2277 IOReadHandler *fd_read,
2278 IOCanRWHandler *fd_can_read,
2281 VLANClientState *vc, **pvc;
2282 vc = qemu_mallocz(sizeof(VLANClientState));
2285 vc->fd_read = fd_read;
2286 vc->fd_can_read = fd_can_read;
2287 vc->opaque = opaque;
2291 pvc = &vlan->first_client;
2292 while (*pvc != NULL)
2293 pvc = &(*pvc)->next;
2298 int qemu_can_send_packet(VLANClientState *vc1)
2300 VLANState *vlan = vc1->vlan;
2301 VLANClientState *vc;
2303 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
2305 if (vc->fd_can_read && !vc->fd_can_read(vc->opaque))
2312 void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
2314 VLANState *vlan = vc1->vlan;
2315 VLANClientState *vc;
2318 printf("vlan %d send:\n", vlan->id);
2319 hex_dump(stdout, buf, size);
2321 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
2323 vc->fd_read(vc->opaque, buf, size);
2328 #if defined(CONFIG_SLIRP)
2330 /* slirp network adapter */
2332 static int slirp_inited;
2333 static VLANClientState *slirp_vc;
2335 int slirp_can_output(void)
2337 return !slirp_vc || qemu_can_send_packet(slirp_vc);
2340 void slirp_output(const uint8_t *pkt, int pkt_len)
2343 printf("slirp output:\n");
2344 hex_dump(stdout, pkt, pkt_len);
2348 qemu_send_packet(slirp_vc, pkt, pkt_len);
2351 static void slirp_receive(void *opaque, const uint8_t *buf, int size)
2354 printf("slirp input:\n");
2355 hex_dump(stdout, buf, size);
2357 slirp_input(buf, size);
2360 static int net_slirp_init(VLANState *vlan)
2362 if (!slirp_inited) {
2366 slirp_vc = qemu_new_vlan_client(vlan,
2367 slirp_receive, NULL, NULL);
2368 snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
2372 static void net_slirp_redir(const char *redir_str)
2377 struct in_addr guest_addr;
2378 int host_port, guest_port;
2380 if (!slirp_inited) {
2386 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2388 if (!strcmp(buf, "tcp")) {
2390 } else if (!strcmp(buf, "udp")) {
2396 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2398 host_port = strtol(buf, &r, 0);
2402 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2404 if (buf[0] == '\0') {
2405 pstrcpy(buf, sizeof(buf), "10.0.2.15");
2407 if (!inet_aton(buf, &guest_addr))
2410 guest_port = strtol(p, &r, 0);
2414 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
2415 fprintf(stderr, "qemu: could not set up redirection\n");
2420 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
2428 static void smb_exit(void)
2432 char filename[1024];
2434 /* erase all the files in the directory */
2435 d = opendir(smb_dir);
2440 if (strcmp(de->d_name, ".") != 0 &&
2441 strcmp(de->d_name, "..") != 0) {
2442 snprintf(filename, sizeof(filename), "%s/%s",
2443 smb_dir, de->d_name);
2451 /* automatic user mode samba server configuration */
2452 void net_slirp_smb(const char *exported_dir)
2454 char smb_conf[1024];
2455 char smb_cmdline[1024];
2458 if (!slirp_inited) {
2463 /* XXX: better tmp dir construction */
2464 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
2465 if (mkdir(smb_dir, 0700) < 0) {
2466 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
2469 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
2471 f = fopen(smb_conf, "w");
2473 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
2480 "socket address=127.0.0.1\n"
2481 "pid directory=%s\n"
2482 "lock directory=%s\n"
2483 "log file=%s/log.smbd\n"
2484 "smb passwd file=%s/smbpasswd\n"
2485 "security = share\n"
2500 snprintf(smb_cmdline, sizeof(smb_cmdline), "/usr/sbin/smbd -s %s",
2503 slirp_add_exec(0, smb_cmdline, 4, 139);
2506 #endif /* !defined(_WIN32) */
2508 #endif /* CONFIG_SLIRP */
2510 #if !defined(_WIN32)
2512 typedef struct TAPState {
2513 VLANClientState *vc;
2517 static void tap_receive(void *opaque, const uint8_t *buf, int size)
2519 TAPState *s = opaque;
2522 ret = write(s->fd, buf, size);
2523 if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
2530 static void tap_send(void *opaque)
2532 TAPState *s = opaque;
2536 size = read(s->fd, buf, sizeof(buf));
2538 qemu_send_packet(s->vc, buf, size);
2544 static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
2548 s = qemu_mallocz(sizeof(TAPState));
2552 s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
2553 qemu_set_fd_handler(s->fd, tap_send, NULL, s);
2554 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
2559 static int tap_open(char *ifname, int ifname_size)
2565 fd = open("/dev/tap", O_RDWR);
2567 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
2572 dev = devname(s.st_rdev, S_IFCHR);
2573 pstrcpy(ifname, ifname_size, dev);
2575 fcntl(fd, F_SETFL, O_NONBLOCK);
2578 #elif defined(__sun__)
2579 static int tap_open(char *ifname, int ifname_size)
2581 fprintf(stderr, "warning: tap_open not yet implemented\n");
2585 static int tap_open(char *ifname, int ifname_size)
2590 fd = open("/dev/net/tun", O_RDWR);
2592 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
2595 memset(&ifr, 0, sizeof(ifr));
2596 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
2597 if (ifname[0] != '\0')
2598 pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
2600 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
2601 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
2603 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
2607 pstrcpy(ifname, ifname_size, ifr.ifr_name);
2608 fcntl(fd, F_SETFL, O_NONBLOCK);
2613 static int net_tap_init(VLANState *vlan, const char *ifname1,
2614 const char *setup_script)
2617 int pid, status, fd;
2622 if (ifname1 != NULL)
2623 pstrcpy(ifname, sizeof(ifname), ifname1);
2626 fd = tap_open(ifname, sizeof(ifname));
2632 if (setup_script[0] != '\0') {
2633 /* try to launch network init script */
2638 *parg++ = (char *)setup_script;
2641 execv(setup_script, args);
2644 while (waitpid(pid, &status, 0) != pid);
2645 if (!WIFEXITED(status) ||
2646 WEXITSTATUS(status) != 0) {
2647 fprintf(stderr, "%s: could not launch network script\n",
2653 s = net_tap_fd_init(vlan, fd);
2656 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
2657 "tap: ifname=%s setup_script=%s", ifname, setup_script);
2661 #endif /* !_WIN32 */
2663 /* network connection */
2664 typedef struct NetSocketState {
2665 VLANClientState *vc;
2667 int state; /* 0 = getting length, 1 = getting data */
2671 struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
2674 typedef struct NetSocketListenState {
2677 } NetSocketListenState;
2679 /* XXX: we consider we can send the whole packet without blocking */
2680 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
2682 NetSocketState *s = opaque;
2686 send_all(s->fd, (const uint8_t *)&len, sizeof(len));
2687 send_all(s->fd, buf, size);
2690 static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
2692 NetSocketState *s = opaque;
2693 sendto(s->fd, buf, size, 0,
2694 (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
2697 static void net_socket_send(void *opaque)
2699 NetSocketState *s = opaque;
2704 size = recv(s->fd, buf1, sizeof(buf1), 0);
2706 err = socket_error();
2707 if (err != EWOULDBLOCK)
2709 } else if (size == 0) {
2710 /* end of connection */
2712 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2718 /* reassemble a packet from the network */
2724 memcpy(s->buf + s->index, buf, l);
2728 if (s->index == 4) {
2730 s->packet_len = ntohl(*(uint32_t *)s->buf);
2736 l = s->packet_len - s->index;
2739 memcpy(s->buf + s->index, buf, l);
2743 if (s->index >= s->packet_len) {
2744 qemu_send_packet(s->vc, s->buf, s->packet_len);
2753 static void net_socket_send_dgram(void *opaque)
2755 NetSocketState *s = opaque;
2758 size = recv(s->fd, s->buf, sizeof(s->buf), 0);
2762 /* end of connection */
2763 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2766 qemu_send_packet(s->vc, s->buf, size);
2769 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
2774 if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
2775 fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
2776 inet_ntoa(mcastaddr->sin_addr),
2777 (int)ntohl(mcastaddr->sin_addr.s_addr));
2781 fd = socket(PF_INET, SOCK_DGRAM, 0);
2783 perror("socket(PF_INET, SOCK_DGRAM)");
2788 ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
2789 (const char *)&val, sizeof(val));
2791 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
2795 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
2801 /* Add host to multicast group */
2802 imr.imr_multiaddr = mcastaddr->sin_addr;
2803 imr.imr_interface.s_addr = htonl(INADDR_ANY);
2805 ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
2806 (const char *)&imr, sizeof(struct ip_mreq));
2808 perror("setsockopt(IP_ADD_MEMBERSHIP)");
2812 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
2814 ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
2815 (const char *)&val, sizeof(val));
2817 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
2821 socket_set_nonblock(fd);
2824 if (fd>=0) close(fd);
2828 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd,
2831 struct sockaddr_in saddr;
2833 socklen_t saddr_len;
2836 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
2837 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
2838 * by ONLY ONE process: we must "clone" this dgram socket --jjo
2842 if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
2844 if (saddr.sin_addr.s_addr==0) {
2845 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
2849 /* clone dgram socket */
2850 newfd = net_socket_mcast_create(&saddr);
2852 /* error already reported by net_socket_mcast_create() */
2856 /* clone newfd to fd, close newfd */
2861 fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
2862 fd, strerror(errno));
2867 s = qemu_mallocz(sizeof(NetSocketState));
2872 s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
2873 qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
2875 /* mcast: save bound address as dst */
2876 if (is_connected) s->dgram_dst=saddr;
2878 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
2879 "socket: fd=%d (%s mcast=%s:%d)",
2880 fd, is_connected? "cloned" : "",
2881 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
2885 static void net_socket_connect(void *opaque)
2887 NetSocketState *s = opaque;
2888 qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
2891 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd,
2895 s = qemu_mallocz(sizeof(NetSocketState));
2899 s->vc = qemu_new_vlan_client(vlan,
2900 net_socket_receive, NULL, s);
2901 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
2902 "socket: fd=%d", fd);
2904 net_socket_connect(s);
2906 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
2911 static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
2914 int so_type=-1, optlen=sizeof(so_type);
2916 if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type, &optlen)< 0) {
2917 fprintf(stderr, "qemu: error: setsockopt(SO_TYPE) for fd=%d failed\n", fd);
2922 return net_socket_fd_init_dgram(vlan, fd, is_connected);
2924 return net_socket_fd_init_stream(vlan, fd, is_connected);
2926 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
2927 fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
2928 return net_socket_fd_init_stream(vlan, fd, is_connected);
2933 static void net_socket_accept(void *opaque)
2935 NetSocketListenState *s = opaque;
2937 struct sockaddr_in saddr;
2942 len = sizeof(saddr);
2943 fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
2944 if (fd < 0 && errno != EINTR) {
2946 } else if (fd >= 0) {
2950 s1 = net_socket_fd_init(s->vlan, fd, 1);
2954 snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
2955 "socket: connection from %s:%d",
2956 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
2960 static int net_socket_listen_init(VLANState *vlan, const char *host_str)
2962 NetSocketListenState *s;
2964 struct sockaddr_in saddr;
2966 if (parse_host_port(&saddr, host_str) < 0)
2969 s = qemu_mallocz(sizeof(NetSocketListenState));
2973 fd = socket(PF_INET, SOCK_STREAM, 0);
2978 socket_set_nonblock(fd);
2980 /* allow fast reuse */
2982 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
2984 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
2989 ret = listen(fd, 0);
2996 qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
3000 static int net_socket_connect_init(VLANState *vlan, const char *host_str)
3003 int fd, connected, ret, err;
3004 struct sockaddr_in saddr;
3006 if (parse_host_port(&saddr, host_str) < 0)
3009 fd = socket(PF_INET, SOCK_STREAM, 0);
3014 socket_set_nonblock(fd);
3018 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
3020 err = socket_error();
3021 if (err == EINTR || err == EWOULDBLOCK) {
3022 } else if (err == EINPROGRESS) {
3034 s = net_socket_fd_init(vlan, fd, connected);
3037 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3038 "socket: connect to %s:%d",
3039 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3043 static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
3047 struct sockaddr_in saddr;
3049 if (parse_host_port(&saddr, host_str) < 0)
3053 fd = net_socket_mcast_create(&saddr);
3057 s = net_socket_fd_init(vlan, fd, 0);
3061 s->dgram_dst = saddr;
3063 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3064 "socket: mcast=%s:%d",
3065 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3070 static int get_param_value(char *buf, int buf_size,
3071 const char *tag, const char *str)
3080 while (*p != '\0' && *p != '=') {
3081 if ((q - option) < sizeof(option) - 1)
3089 if (!strcmp(tag, option)) {
3091 while (*p != '\0' && *p != ',') {
3092 if ((q - buf) < buf_size - 1)
3099 while (*p != '\0' && *p != ',') {
3110 int net_client_init(const char *str)
3121 while (*p != '\0' && *p != ',') {
3122 if ((q - device) < sizeof(device) - 1)
3130 if (get_param_value(buf, sizeof(buf), "vlan", p)) {
3131 vlan_id = strtol(buf, NULL, 0);
3133 vlan = qemu_find_vlan(vlan_id);
3135 fprintf(stderr, "Could not create vlan %d\n", vlan_id);
3138 if (!strcmp(device, "nic")) {
3142 if (nb_nics >= MAX_NICS) {
3143 fprintf(stderr, "Too Many NICs\n");
3146 nd = &nd_table[nb_nics];
3147 macaddr = nd->macaddr;
3153 macaddr[5] = 0x56 + nb_nics;
3155 if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
3156 if (parse_macaddr(macaddr, buf) < 0) {
3157 fprintf(stderr, "invalid syntax for ethernet address\n");
3161 if (get_param_value(buf, sizeof(buf), "model", p)) {
3162 nd->model = strdup(buf);
3168 if (!strcmp(device, "none")) {
3169 /* does nothing. It is needed to signal that no network cards
3174 if (!strcmp(device, "user")) {
3175 if (get_param_value(buf, sizeof(buf), "hostname", p)) {
3176 pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
3178 ret = net_slirp_init(vlan);
3182 if (!strcmp(device, "tap")) {
3184 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
3185 fprintf(stderr, "tap: no interface name\n");
3188 ret = tap_win32_init(vlan, ifname);
3191 if (!strcmp(device, "tap")) {
3193 char setup_script[1024];
3195 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
3196 fd = strtol(buf, NULL, 0);
3198 if (net_tap_fd_init(vlan, fd))
3201 get_param_value(ifname, sizeof(ifname), "ifname", p);
3202 if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
3203 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
3205 ret = net_tap_init(vlan, ifname, setup_script);
3209 if (!strcmp(device, "socket")) {
3210 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
3212 fd = strtol(buf, NULL, 0);
3214 if (net_socket_fd_init(vlan, fd, 1))
3216 } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
3217 ret = net_socket_listen_init(vlan, buf);
3218 } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
3219 ret = net_socket_connect_init(vlan, buf);
3220 } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
3221 ret = net_socket_mcast_init(vlan, buf);
3223 fprintf(stderr, "Unknown socket options: %s\n", p);
3228 fprintf(stderr, "Unknown network device: %s\n", device);
3232 fprintf(stderr, "Could not initialize device '%s'\n", device);
3238 void do_info_network(void)
3241 VLANClientState *vc;
3243 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
3244 term_printf("VLAN %d devices:\n", vlan->id);
3245 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
3246 term_printf(" %s\n", vc->info_str);
3250 /***********************************************************/
3253 static USBPort *used_usb_ports;
3254 static USBPort *free_usb_ports;
3256 /* ??? Maybe change this to register a hub to keep track of the topology. */
3257 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
3258 usb_attachfn attach)
3260 port->opaque = opaque;
3261 port->index = index;
3262 port->attach = attach;
3263 port->next = free_usb_ports;
3264 free_usb_ports = port;
3267 static int usb_device_add(const char *devname)
3273 if (!free_usb_ports)
3276 if (strstart(devname, "host:", &p)) {
3277 dev = usb_host_device_open(p);
3278 } else if (!strcmp(devname, "mouse")) {
3279 dev = usb_mouse_init();
3280 } else if (!strcmp(devname, "tablet")) {
3281 dev = usb_tablet_init();
3288 /* Find a USB port to add the device to. */
3289 port = free_usb_ports;
3293 /* Create a new hub and chain it on. */
3294 free_usb_ports = NULL;
3295 port->next = used_usb_ports;
3296 used_usb_ports = port;
3298 hub = usb_hub_init(VM_USB_HUB_SIZE);
3299 usb_attach(port, hub);
3300 port = free_usb_ports;
3303 free_usb_ports = port->next;
3304 port->next = used_usb_ports;
3305 used_usb_ports = port;
3306 usb_attach(port, dev);
3310 static int usb_device_del(const char *devname)
3317 if (!used_usb_ports)
3320 p = strchr(devname, '.');
3323 bus_num = strtoul(devname, NULL, 0);
3324 addr = strtoul(p + 1, NULL, 0);
3328 lastp = &used_usb_ports;
3329 port = used_usb_ports;
3330 while (port && port->dev->addr != addr) {
3331 lastp = &port->next;
3338 *lastp = port->next;
3339 usb_attach(port, NULL);
3340 port->next = free_usb_ports;
3341 free_usb_ports = port;
3345 void do_usb_add(const char *devname)
3348 ret = usb_device_add(devname);
3350 term_printf("Could not add USB device '%s'\n", devname);
3353 void do_usb_del(const char *devname)
3356 ret = usb_device_del(devname);
3358 term_printf("Could not remove USB device '%s'\n", devname);
3365 const char *speed_str;
3368 term_printf("USB support not enabled\n");
3372 for (port = used_usb_ports; port; port = port->next) {
3376 switch(dev->speed) {
3380 case USB_SPEED_FULL:
3383 case USB_SPEED_HIGH:
3390 term_printf(" Device %d.%d, speed %s Mb/s\n",
3391 0, dev->addr, speed_str);
3395 /***********************************************************/
3398 static char *pid_filename;
3400 /* Remove PID file. Called on normal exit */
3402 static void remove_pidfile(void)
3404 unlink (pid_filename);
3407 static void create_pidfile(const char *filename)
3409 struct stat pidstat;
3412 /* Try to write our PID to the named file */
3413 if (stat(filename, &pidstat) < 0) {
3414 if (errno == ENOENT) {
3415 if ((f = fopen (filename, "w")) == NULL) {
3416 perror("Opening pidfile");
3419 fprintf(f, "%d\n", getpid());
3421 pid_filename = qemu_strdup(filename);
3422 if (!pid_filename) {
3423 fprintf(stderr, "Could not save PID filename");
3426 atexit(remove_pidfile);
3429 fprintf(stderr, "%s already exists. Remove it and try again.\n",
3435 /***********************************************************/
3438 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
3442 static void dumb_resize(DisplayState *ds, int w, int h)
3446 static void dumb_refresh(DisplayState *ds)
3451 void dumb_display_init(DisplayState *ds)
3456 ds->dpy_update = dumb_update;
3457 ds->dpy_resize = dumb_resize;
3458 ds->dpy_refresh = dumb_refresh;
3461 #if !defined(CONFIG_SOFTMMU)
3462 /***********************************************************/
3463 /* cpu signal handler */
3464 static void host_segv_handler(int host_signum, siginfo_t *info,
3467 if (cpu_signal_handler(host_signum, info, puc))
3469 if (stdio_nb_clients > 0)
3475 /***********************************************************/
3478 #define MAX_IO_HANDLERS 64
3480 typedef struct IOHandlerRecord {
3482 IOCanRWHandler *fd_read_poll;
3484 IOHandler *fd_write;
3486 /* temporary data */
3488 struct IOHandlerRecord *next;
3491 static IOHandlerRecord *first_io_handler;
3493 /* XXX: fd_read_poll should be suppressed, but an API change is
3494 necessary in the character devices to suppress fd_can_read(). */
3495 int qemu_set_fd_handler2(int fd,
3496 IOCanRWHandler *fd_read_poll,
3498 IOHandler *fd_write,
3501 IOHandlerRecord **pioh, *ioh;
3503 if (!fd_read && !fd_write) {
3504 pioh = &first_io_handler;
3509 if (ioh->fd == fd) {
3517 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3521 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
3524 ioh->next = first_io_handler;
3525 first_io_handler = ioh;
3528 ioh->fd_read_poll = fd_read_poll;
3529 ioh->fd_read = fd_read;
3530 ioh->fd_write = fd_write;
3531 ioh->opaque = opaque;
3536 int qemu_set_fd_handler(int fd,
3538 IOHandler *fd_write,
3541 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
3544 /***********************************************************/
3545 /* Polling handling */
3547 typedef struct PollingEntry {
3550 struct PollingEntry *next;
3553 static PollingEntry *first_polling_entry;
3555 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
3557 PollingEntry **ppe, *pe;
3558 pe = qemu_mallocz(sizeof(PollingEntry));
3562 pe->opaque = opaque;
3563 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
3568 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
3570 PollingEntry **ppe, *pe;
3571 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
3573 if (pe->func == func && pe->opaque == opaque) {
3581 /***********************************************************/
3582 /* savevm/loadvm support */
3584 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
3586 fwrite(buf, 1, size, f);
3589 void qemu_put_byte(QEMUFile *f, int v)
3594 void qemu_put_be16(QEMUFile *f, unsigned int v)
3596 qemu_put_byte(f, v >> 8);
3597 qemu_put_byte(f, v);
3600 void qemu_put_be32(QEMUFile *f, unsigned int v)
3602 qemu_put_byte(f, v >> 24);
3603 qemu_put_byte(f, v >> 16);
3604 qemu_put_byte(f, v >> 8);
3605 qemu_put_byte(f, v);
3608 void qemu_put_be64(QEMUFile *f, uint64_t v)
3610 qemu_put_be32(f, v >> 32);
3611 qemu_put_be32(f, v);
3614 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size)
3616 return fread(buf, 1, size, f);
3619 int qemu_get_byte(QEMUFile *f)
3629 unsigned int qemu_get_be16(QEMUFile *f)
3632 v = qemu_get_byte(f) << 8;
3633 v |= qemu_get_byte(f);
3637 unsigned int qemu_get_be32(QEMUFile *f)
3640 v = qemu_get_byte(f) << 24;
3641 v |= qemu_get_byte(f) << 16;
3642 v |= qemu_get_byte(f) << 8;
3643 v |= qemu_get_byte(f);
3647 uint64_t qemu_get_be64(QEMUFile *f)
3650 v = (uint64_t)qemu_get_be32(f) << 32;
3651 v |= qemu_get_be32(f);
3655 int64_t qemu_ftell(QEMUFile *f)
3660 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
3662 if (fseek(f, pos, whence) < 0)
3667 typedef struct SaveStateEntry {
3671 SaveStateHandler *save_state;
3672 LoadStateHandler *load_state;
3674 struct SaveStateEntry *next;
3677 static SaveStateEntry *first_se;
3679 int register_savevm(const char *idstr,
3682 SaveStateHandler *save_state,
3683 LoadStateHandler *load_state,
3686 SaveStateEntry *se, **pse;
3688 se = qemu_malloc(sizeof(SaveStateEntry));
3691 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
3692 se->instance_id = instance_id;
3693 se->version_id = version_id;
3694 se->save_state = save_state;
3695 se->load_state = load_state;
3696 se->opaque = opaque;
3699 /* add at the end of list */
3701 while (*pse != NULL)
3702 pse = &(*pse)->next;
3707 #define QEMU_VM_FILE_MAGIC 0x5145564d
3708 #define QEMU_VM_FILE_VERSION 0x00000001
3710 int qemu_savevm(const char *filename)
3714 int len, len_pos, cur_pos, saved_vm_running, ret;
3716 saved_vm_running = vm_running;
3719 f = fopen(filename, "wb");
3725 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
3726 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
3728 for(se = first_se; se != NULL; se = se->next) {
3730 len = strlen(se->idstr);
3731 qemu_put_byte(f, len);
3732 qemu_put_buffer(f, se->idstr, len);
3734 qemu_put_be32(f, se->instance_id);
3735 qemu_put_be32(f, se->version_id);
3737 /* record size: filled later */
3739 qemu_put_be32(f, 0);
3741 se->save_state(f, se->opaque);
3743 /* fill record size */
3745 len = ftell(f) - len_pos - 4;
3746 fseek(f, len_pos, SEEK_SET);
3747 qemu_put_be32(f, len);
3748 fseek(f, cur_pos, SEEK_SET);
3754 if (saved_vm_running)
3759 static SaveStateEntry *find_se(const char *idstr, int instance_id)
3763 for(se = first_se; se != NULL; se = se->next) {
3764 if (!strcmp(se->idstr, idstr) &&
3765 instance_id == se->instance_id)
3771 int qemu_loadvm(const char *filename)
3775 int len, cur_pos, ret, instance_id, record_len, version_id;
3776 int saved_vm_running;
3780 saved_vm_running = vm_running;
3783 f = fopen(filename, "rb");
3789 v = qemu_get_be32(f);
3790 if (v != QEMU_VM_FILE_MAGIC)
3792 v = qemu_get_be32(f);
3793 if (v != QEMU_VM_FILE_VERSION) {
3800 len = qemu_get_byte(f);
3803 qemu_get_buffer(f, idstr, len);
3805 instance_id = qemu_get_be32(f);
3806 version_id = qemu_get_be32(f);
3807 record_len = qemu_get_be32(f);
3809 printf("idstr=%s instance=0x%x version=%d len=%d\n",
3810 idstr, instance_id, version_id, record_len);
3813 se = find_se(idstr, instance_id);
3815 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
3816 instance_id, idstr);
3818 ret = se->load_state(f, se->opaque, version_id);
3820 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
3821 instance_id, idstr);
3824 /* always seek to exact end of record */
3825 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
3830 if (saved_vm_running)
3835 /***********************************************************/
3836 /* cpu save/restore */
3838 #if defined(TARGET_I386)
3840 static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
3842 qemu_put_be32(f, dt->selector);
3843 qemu_put_betl(f, dt->base);
3844 qemu_put_be32(f, dt->limit);
3845 qemu_put_be32(f, dt->flags);
3848 static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
3850 dt->selector = qemu_get_be32(f);
3851 dt->base = qemu_get_betl(f);
3852 dt->limit = qemu_get_be32(f);
3853 dt->flags = qemu_get_be32(f);
3856 void cpu_save(QEMUFile *f, void *opaque)
3858 CPUState *env = opaque;
3859 uint16_t fptag, fpus, fpuc, fpregs_format;
3863 for(i = 0; i < CPU_NB_REGS; i++)
3864 qemu_put_betls(f, &env->regs[i]);
3865 qemu_put_betls(f, &env->eip);
3866 qemu_put_betls(f, &env->eflags);
3867 hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
3868 qemu_put_be32s(f, &hflags);
3872 fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
3874 for(i = 0; i < 8; i++) {
3875 fptag |= ((!env->fptags[i]) << i);
3878 qemu_put_be16s(f, &fpuc);
3879 qemu_put_be16s(f, &fpus);
3880 qemu_put_be16s(f, &fptag);
3882 #ifdef USE_X86LDOUBLE
3887 qemu_put_be16s(f, &fpregs_format);
3889 for(i = 0; i < 8; i++) {
3890 #ifdef USE_X86LDOUBLE
3894 /* we save the real CPU data (in case of MMX usage only 'mant'
3895 contains the MMX register */
3896 cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
3897 qemu_put_be64(f, mant);
3898 qemu_put_be16(f, exp);
3901 /* if we use doubles for float emulation, we save the doubles to
3902 avoid losing information in case of MMX usage. It can give
3903 problems if the image is restored on a CPU where long
3904 doubles are used instead. */
3905 qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
3909 for(i = 0; i < 6; i++)
3910 cpu_put_seg(f, &env->segs[i]);
3911 cpu_put_seg(f, &env->ldt);
3912 cpu_put_seg(f, &env->tr);
3913 cpu_put_seg(f, &env->gdt);
3914 cpu_put_seg(f, &env->idt);
3916 qemu_put_be32s(f, &env->sysenter_cs);
3917 qemu_put_be32s(f, &env->sysenter_esp);
3918 qemu_put_be32s(f, &env->sysenter_eip);
3920 qemu_put_betls(f, &env->cr[0]);
3921 qemu_put_betls(f, &env->cr[2]);
3922 qemu_put_betls(f, &env->cr[3]);
3923 qemu_put_betls(f, &env->cr[4]);
3925 for(i = 0; i < 8; i++)
3926 qemu_put_betls(f, &env->dr[i]);
3929 qemu_put_be32s(f, &env->a20_mask);
3932 qemu_put_be32s(f, &env->mxcsr);
3933 for(i = 0; i < CPU_NB_REGS; i++) {
3934 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
3935 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
3938 #ifdef TARGET_X86_64
3939 qemu_put_be64s(f, &env->efer);
3940 qemu_put_be64s(f, &env->star);
3941 qemu_put_be64s(f, &env->lstar);
3942 qemu_put_be64s(f, &env->cstar);
3943 qemu_put_be64s(f, &env->fmask);
3944 qemu_put_be64s(f, &env->kernelgsbase);
3948 #ifdef USE_X86LDOUBLE
3949 /* XXX: add that in a FPU generic layer */
3950 union x86_longdouble {
3955 #define MANTD1(fp) (fp & ((1LL << 52) - 1))
3956 #define EXPBIAS1 1023
3957 #define EXPD1(fp) ((fp >> 52) & 0x7FF)
3958 #define SIGND1(fp) ((fp >> 32) & 0x80000000)
3960 static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
3964 p->mant = (MANTD1(temp) << 11) | (1LL << 63);
3965 /* exponent + sign */
3966 e = EXPD1(temp) - EXPBIAS1 + 16383;
3967 e |= SIGND1(temp) >> 16;
3972 int cpu_load(QEMUFile *f, void *opaque, int version_id)
3974 CPUState *env = opaque;
3977 uint16_t fpus, fpuc, fptag, fpregs_format;
3979 if (version_id != 3)
3981 for(i = 0; i < CPU_NB_REGS; i++)
3982 qemu_get_betls(f, &env->regs[i]);
3983 qemu_get_betls(f, &env->eip);
3984 qemu_get_betls(f, &env->eflags);
3985 qemu_get_be32s(f, &hflags);
3987 qemu_get_be16s(f, &fpuc);
3988 qemu_get_be16s(f, &fpus);
3989 qemu_get_be16s(f, &fptag);
3990 qemu_get_be16s(f, &fpregs_format);
3992 /* NOTE: we cannot always restore the FPU state if the image come
3993 from a host with a different 'USE_X86LDOUBLE' define. We guess
3994 if we are in an MMX state to restore correctly in that case. */
3995 guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
3996 for(i = 0; i < 8; i++) {
4000 switch(fpregs_format) {
4002 mant = qemu_get_be64(f);
4003 exp = qemu_get_be16(f);
4004 #ifdef USE_X86LDOUBLE
4005 env->fpregs[i].d = cpu_set_fp80(mant, exp);
4007 /* difficult case */
4009 env->fpregs[i].mmx.MMX_Q(0) = mant;
4011 env->fpregs[i].d = cpu_set_fp80(mant, exp);
4015 mant = qemu_get_be64(f);
4016 #ifdef USE_X86LDOUBLE
4018 union x86_longdouble *p;
4019 /* difficult case */
4020 p = (void *)&env->fpregs[i];
4025 fp64_to_fp80(p, mant);
4029 env->fpregs[i].mmx.MMX_Q(0) = mant;
4038 /* XXX: restore FPU round state */
4039 env->fpstt = (fpus >> 11) & 7;
4040 env->fpus = fpus & ~0x3800;
4042 for(i = 0; i < 8; i++) {
4043 env->fptags[i] = (fptag >> i) & 1;
4046 for(i = 0; i < 6; i++)
4047 cpu_get_seg(f, &env->segs[i]);
4048 cpu_get_seg(f, &env->ldt);
4049 cpu_get_seg(f, &env->tr);
4050 cpu_get_seg(f, &env->gdt);
4051 cpu_get_seg(f, &env->idt);
4053 qemu_get_be32s(f, &env->sysenter_cs);
4054 qemu_get_be32s(f, &env->sysenter_esp);
4055 qemu_get_be32s(f, &env->sysenter_eip);
4057 qemu_get_betls(f, &env->cr[0]);
4058 qemu_get_betls(f, &env->cr[2]);
4059 qemu_get_betls(f, &env->cr[3]);
4060 qemu_get_betls(f, &env->cr[4]);
4062 for(i = 0; i < 8; i++)
4063 qemu_get_betls(f, &env->dr[i]);
4066 qemu_get_be32s(f, &env->a20_mask);
4068 qemu_get_be32s(f, &env->mxcsr);
4069 for(i = 0; i < CPU_NB_REGS; i++) {
4070 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
4071 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
4074 #ifdef TARGET_X86_64
4075 qemu_get_be64s(f, &env->efer);
4076 qemu_get_be64s(f, &env->star);
4077 qemu_get_be64s(f, &env->lstar);
4078 qemu_get_be64s(f, &env->cstar);
4079 qemu_get_be64s(f, &env->fmask);
4080 qemu_get_be64s(f, &env->kernelgsbase);
4083 /* XXX: compute hflags from scratch, except for CPL and IIF */
4084 env->hflags = hflags;
4089 #elif defined(TARGET_PPC)
4090 void cpu_save(QEMUFile *f, void *opaque)
4094 int cpu_load(QEMUFile *f, void *opaque, int version_id)
4099 #elif defined(TARGET_MIPS)
4100 void cpu_save(QEMUFile *f, void *opaque)
4104 int cpu_load(QEMUFile *f, void *opaque, int version_id)
4109 #elif defined(TARGET_SPARC)
4110 void cpu_save(QEMUFile *f, void *opaque)
4112 CPUState *env = opaque;
4116 for(i = 0; i < 8; i++)
4117 qemu_put_betls(f, &env->gregs[i]);
4118 for(i = 0; i < NWINDOWS * 16; i++)
4119 qemu_put_betls(f, &env->regbase[i]);
4122 for(i = 0; i < TARGET_FPREGS; i++) {
4128 qemu_put_betl(f, u.i);
4131 qemu_put_betls(f, &env->pc);
4132 qemu_put_betls(f, &env->npc);
4133 qemu_put_betls(f, &env->y);
4135 qemu_put_be32(f, tmp);
4136 qemu_put_betls(f, &env->fsr);
4137 qemu_put_betls(f, &env->tbr);
4138 #ifndef TARGET_SPARC64
4139 qemu_put_be32s(f, &env->wim);
4141 for(i = 0; i < 16; i++)
4142 qemu_put_be32s(f, &env->mmuregs[i]);
4146 int cpu_load(QEMUFile *f, void *opaque, int version_id)
4148 CPUState *env = opaque;
4152 for(i = 0; i < 8; i++)
4153 qemu_get_betls(f, &env->gregs[i]);
4154 for(i = 0; i < NWINDOWS * 16; i++)
4155 qemu_get_betls(f, &env->regbase[i]);
4158 for(i = 0; i < TARGET_FPREGS; i++) {
4163 u.i = qemu_get_betl(f);
4167 qemu_get_betls(f, &env->pc);
4168 qemu_get_betls(f, &env->npc);
4169 qemu_get_betls(f, &env->y);
4170 tmp = qemu_get_be32(f);
4171 env->cwp = 0; /* needed to ensure that the wrapping registers are
4172 correctly updated */
4174 qemu_get_betls(f, &env->fsr);
4175 qemu_get_betls(f, &env->tbr);
4176 #ifndef TARGET_SPARC64
4177 qemu_get_be32s(f, &env->wim);
4179 for(i = 0; i < 16; i++)
4180 qemu_get_be32s(f, &env->mmuregs[i]);
4186 #elif defined(TARGET_ARM)
4188 /* ??? Need to implement these. */
4189 void cpu_save(QEMUFile *f, void *opaque)
4193 int cpu_load(QEMUFile *f, void *opaque, int version_id)
4200 #warning No CPU save/restore functions
4204 /***********************************************************/
4205 /* ram save/restore */
4207 /* we just avoid storing empty pages */
4208 static void ram_put_page(QEMUFile *f, const uint8_t *buf, int len)
4213 for(i = 1; i < len; i++) {
4217 qemu_put_byte(f, 1);
4218 qemu_put_byte(f, v);
4221 qemu_put_byte(f, 0);
4222 qemu_put_buffer(f, buf, len);
4225 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
4229 v = qemu_get_byte(f);
4232 if (qemu_get_buffer(f, buf, len) != len)
4236 v = qemu_get_byte(f);
4237 memset(buf, v, len);
4245 static void ram_save(QEMUFile *f, void *opaque)
4248 qemu_put_be32(f, phys_ram_size);
4249 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
4250 ram_put_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
4254 static int ram_load(QEMUFile *f, void *opaque, int version_id)
4258 if (version_id != 1)
4260 if (qemu_get_be32(f) != phys_ram_size)
4262 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
4263 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
4270 /***********************************************************/
4271 /* machine registration */
4273 QEMUMachine *first_machine = NULL;
4275 int qemu_register_machine(QEMUMachine *m)
4278 pm = &first_machine;
4286 QEMUMachine *find_machine(const char *name)
4290 for(m = first_machine; m != NULL; m = m->next) {
4291 if (!strcmp(m->name, name))
4297 /***********************************************************/
4298 /* main execution loop */
4300 void gui_update(void *opaque)
4302 display_state.dpy_refresh(&display_state);
4303 qemu_mod_timer(gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
4306 struct vm_change_state_entry {
4307 VMChangeStateHandler *cb;
4309 LIST_ENTRY (vm_change_state_entry) entries;
4312 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
4314 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
4317 VMChangeStateEntry *e;
4319 e = qemu_mallocz(sizeof (*e));
4325 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
4329 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
4331 LIST_REMOVE (e, entries);
4335 static void vm_state_notify(int running)
4337 VMChangeStateEntry *e;
4339 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
4340 e->cb(e->opaque, running);
4344 /* XXX: support several handlers */
4345 static VMStopHandler *vm_stop_cb;
4346 static void *vm_stop_opaque;
4348 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
4351 vm_stop_opaque = opaque;
4355 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
4369 void vm_stop(int reason)
4372 cpu_disable_ticks();
4376 vm_stop_cb(vm_stop_opaque, reason);
4383 /* reset/shutdown handler */
4385 typedef struct QEMUResetEntry {
4386 QEMUResetHandler *func;
4388 struct QEMUResetEntry *next;
4391 static QEMUResetEntry *first_reset_entry;
4392 static int reset_requested;
4393 static int shutdown_requested;
4394 static int powerdown_requested;
4396 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
4398 QEMUResetEntry **pre, *re;
4400 pre = &first_reset_entry;
4401 while (*pre != NULL)
4402 pre = &(*pre)->next;
4403 re = qemu_mallocz(sizeof(QEMUResetEntry));
4405 re->opaque = opaque;
4410 void qemu_system_reset(void)
4414 /* reset all devices */
4415 for(re = first_reset_entry; re != NULL; re = re->next) {
4416 re->func(re->opaque);
4420 void qemu_system_reset_request(void)
4422 reset_requested = 1;
4424 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
4427 void qemu_system_shutdown_request(void)
4429 shutdown_requested = 1;
4431 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
4434 void qemu_system_powerdown_request(void)
4436 powerdown_requested = 1;
4438 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
4441 void main_loop_wait(int timeout)
4443 IOHandlerRecord *ioh, *ioh_next;
4444 fd_set rfds, wfds, xfds;
4450 /* XXX: need to suppress polling by better using win32 events */
4452 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
4453 ret |= pe->func(pe->opaque);
4456 if (ret == 0 && timeout > 0) {
4460 hEvents[0] = host_alarm;
4461 ret = WaitForMultipleObjects(1, hEvents, FALSE, timeout);
4463 case WAIT_OBJECT_0 + 0:
4468 err = GetLastError();
4469 fprintf(stderr, "Wait error %d %d\n", ret, err);
4474 /* poll any events */
4475 /* XXX: separate device handlers from system ones */
4480 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4482 (!ioh->fd_read_poll ||
4483 ioh->fd_read_poll(ioh->opaque) != 0)) {
4484 FD_SET(ioh->fd, &rfds);
4488 if (ioh->fd_write) {
4489 FD_SET(ioh->fd, &wfds);
4499 tv.tv_usec = timeout * 1000;
4501 #if defined(CONFIG_SLIRP)
4503 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
4506 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
4508 /* XXX: better handling of removal */
4509 for(ioh = first_io_handler; ioh != NULL; ioh = ioh_next) {
4510 ioh_next = ioh->next;
4511 if (FD_ISSET(ioh->fd, &rfds)) {
4512 ioh->fd_read(ioh->opaque);
4514 if (FD_ISSET(ioh->fd, &wfds)) {
4515 ioh->fd_write(ioh->opaque);
4519 #if defined(CONFIG_SLIRP)
4526 slirp_select_poll(&rfds, &wfds, &xfds);
4534 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
4535 qemu_get_clock(vm_clock));
4536 /* run dma transfers, if any */
4540 /* real time timers */
4541 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
4542 qemu_get_clock(rt_clock));
4545 static CPUState *cur_cpu;
4550 #ifdef CONFIG_PROFILER
4555 cur_cpu = first_cpu;
4562 env = env->next_cpu;
4565 #ifdef CONFIG_PROFILER
4566 ti = profile_getclock();
4568 ret = cpu_exec(env);
4569 #ifdef CONFIG_PROFILER
4570 qemu_time += profile_getclock() - ti;
4572 if (ret != EXCP_HALTED)
4574 /* all CPUs are halted ? */
4575 if (env == cur_cpu) {
4582 if (shutdown_requested) {
4583 ret = EXCP_INTERRUPT;
4586 if (reset_requested) {
4587 reset_requested = 0;
4588 qemu_system_reset();
4589 ret = EXCP_INTERRUPT;
4591 if (powerdown_requested) {
4592 powerdown_requested = 0;
4593 qemu_system_powerdown();
4594 ret = EXCP_INTERRUPT;
4596 if (ret == EXCP_DEBUG) {
4597 vm_stop(EXCP_DEBUG);
4599 /* if hlt instruction, we wait until the next IRQ */
4600 /* XXX: use timeout computed from timers */
4601 if (ret == EXCP_HLT)
4608 #ifdef CONFIG_PROFILER
4609 ti = profile_getclock();
4611 main_loop_wait(timeout);
4612 #ifdef CONFIG_PROFILER
4613 dev_time += profile_getclock() - ti;
4616 cpu_disable_ticks();
4622 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2005 Fabrice Bellard\n"
4623 "usage: %s [options] [disk_image]\n"
4625 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4627 "Standard options:\n"
4628 "-M machine select emulated machine (-M ? for list)\n"
4629 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
4630 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
4631 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
4632 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
4633 "-boot [a|c|d] boot on floppy (a), hard disk (c) or CD-ROM (d)\n"
4634 "-snapshot write to temporary files instead of disk image files\n"
4635 "-m megs set virtual RAM size to megs MB [default=%d]\n"
4636 "-smp n set the number of CPUs to 'n' [default=1]\n"
4637 "-nographic disable graphical output and redirect serial I/Os to console\n"
4639 "-k language use keyboard layout (for example \"fr\" for French)\n"
4642 "-audio-help print list of audio drivers and their options\n"
4643 "-soundhw c1,... enable audio support\n"
4644 " and only specified sound cards (comma separated list)\n"
4645 " use -soundhw ? to get the list of supported cards\n"
4646 " use -soundhw all to enable all of them\n"
4648 "-localtime set the real time clock to local time [default=utc]\n"
4649 "-full-screen start in full screen\n"
4651 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
4653 "-usb enable the USB driver (will be the default soon)\n"
4654 "-usbdevice name add the host or guest USB device 'name'\n"
4655 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
4656 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
4659 "Network options:\n"
4660 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
4661 " create a new Network Interface Card and connect it to VLAN 'n'\n"
4663 "-net user[,vlan=n][,hostname=host]\n"
4664 " connect the user mode network stack to VLAN 'n' and send\n"
4665 " hostname 'host' to DHCP clients\n"
4668 "-net tap[,vlan=n],ifname=name\n"
4669 " connect the host TAP network interface to VLAN 'n'\n"
4671 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file]\n"
4672 " connect the host TAP network interface to VLAN 'n' and use\n"
4673 " the network script 'file' (default=%s);\n"
4674 " use 'fd=h' to connect to an already opened TAP interface\n"
4676 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
4677 " connect the vlan 'n' to another VLAN using a socket connection\n"
4678 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
4679 " connect the vlan 'n' to multicast maddr and port\n"
4680 "-net none use it alone to have zero network devices; if no -net option\n"
4681 " is provided, the default is '-net nic -net user'\n"
4684 "-tftp prefix allow tftp access to files starting with prefix [-net user]\n"
4686 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
4688 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
4689 " redirect TCP or UDP connections from host to guest [-net user]\n"
4692 "Linux boot specific:\n"
4693 "-kernel bzImage use 'bzImage' as kernel image\n"
4694 "-append cmdline use 'cmdline' as kernel command line\n"
4695 "-initrd file use 'file' as initial ram disk\n"
4697 "Debug/Expert options:\n"
4698 "-monitor dev redirect the monitor to char device 'dev'\n"
4699 "-serial dev redirect the serial port to char device 'dev'\n"
4700 "-parallel dev redirect the parallel port to char device 'dev'\n"
4701 "-pidfile file Write PID to 'file'\n"
4702 "-S freeze CPU at startup (use 'c' to start execution)\n"
4703 "-s wait gdb connection to port %d\n"
4704 "-p port change gdb connection port\n"
4705 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
4706 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
4707 " translation (t=none or lba) (usually qemu can guess them)\n"
4708 "-L path set the directory for the BIOS and VGA BIOS\n"
4710 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
4711 "-no-kqemu disable KQEMU kernel module usage\n"
4713 #ifdef USE_CODE_COPY
4714 "-no-code-copy disable code copy acceleration\n"
4717 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
4718 " (default is CL-GD5446 PCI VGA)\n"
4719 "-no-acpi disable ACPI\n"
4721 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
4722 "-vnc display start a VNC server on display\n"
4724 "During emulation, the following keys are useful:\n"
4725 "ctrl-alt-f toggle full screen\n"
4726 "ctrl-alt-n switch to virtual console 'n'\n"
4727 "ctrl-alt toggle mouse and keyboard grab\n"
4729 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4731 #ifdef CONFIG_SOFTMMU
4738 DEFAULT_NETWORK_SCRIPT,
4740 DEFAULT_GDBSTUB_PORT,
4742 #ifndef CONFIG_SOFTMMU
4744 "NOTE: this version of QEMU is faster but it needs slightly patched OSes to\n"
4745 "work. Please use the 'qemu' executable to have a more accurate (but slower)\n"
4751 #define HAS_ARG 0x0001
4765 QEMU_OPTION_snapshot,
4767 QEMU_OPTION_nographic,
4769 QEMU_OPTION_audio_help,
4770 QEMU_OPTION_soundhw,
4788 QEMU_OPTION_no_code_copy,
4790 QEMU_OPTION_localtime,
4791 QEMU_OPTION_cirrusvga,
4793 QEMU_OPTION_std_vga,
4794 QEMU_OPTION_monitor,
4796 QEMU_OPTION_parallel,
4798 QEMU_OPTION_full_screen,
4799 QEMU_OPTION_pidfile,
4800 QEMU_OPTION_no_kqemu,
4801 QEMU_OPTION_kernel_kqemu,
4802 QEMU_OPTION_win2k_hack,
4804 QEMU_OPTION_usbdevice,
4807 QEMU_OPTION_no_acpi,
4810 typedef struct QEMUOption {
4816 const QEMUOption qemu_options[] = {
4817 { "h", 0, QEMU_OPTION_h },
4819 { "M", HAS_ARG, QEMU_OPTION_M },
4820 { "fda", HAS_ARG, QEMU_OPTION_fda },
4821 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
4822 { "hda", HAS_ARG, QEMU_OPTION_hda },
4823 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
4824 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
4825 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
4826 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
4827 { "boot", HAS_ARG, QEMU_OPTION_boot },
4828 { "snapshot", 0, QEMU_OPTION_snapshot },
4829 { "m", HAS_ARG, QEMU_OPTION_m },
4830 { "nographic", 0, QEMU_OPTION_nographic },
4831 { "k", HAS_ARG, QEMU_OPTION_k },
4833 { "audio-help", 0, QEMU_OPTION_audio_help },
4834 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
4837 { "net", HAS_ARG, QEMU_OPTION_net},
4839 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
4841 { "smb", HAS_ARG, QEMU_OPTION_smb },
4843 { "redir", HAS_ARG, QEMU_OPTION_redir },
4846 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
4847 { "append", HAS_ARG, QEMU_OPTION_append },
4848 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
4850 { "S", 0, QEMU_OPTION_S },
4851 { "s", 0, QEMU_OPTION_s },
4852 { "p", HAS_ARG, QEMU_OPTION_p },
4853 { "d", HAS_ARG, QEMU_OPTION_d },
4854 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
4855 { "L", HAS_ARG, QEMU_OPTION_L },
4856 { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
4858 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
4859 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
4861 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
4862 { "g", 1, QEMU_OPTION_g },
4864 { "localtime", 0, QEMU_OPTION_localtime },
4865 { "std-vga", 0, QEMU_OPTION_std_vga },
4866 { "monitor", 1, QEMU_OPTION_monitor },
4867 { "serial", 1, QEMU_OPTION_serial },
4868 { "parallel", 1, QEMU_OPTION_parallel },
4869 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
4870 { "full-screen", 0, QEMU_OPTION_full_screen },
4871 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
4872 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
4873 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
4874 { "smp", HAS_ARG, QEMU_OPTION_smp },
4875 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
4877 /* temporary options */
4878 { "usb", 0, QEMU_OPTION_usb },
4879 { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
4880 { "no-acpi", 0, QEMU_OPTION_no_acpi },
4884 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
4886 /* this stack is only used during signal handling */
4887 #define SIGNAL_STACK_SIZE 32768
4889 static uint8_t *signal_stack;
4893 /* password input */
4895 static BlockDriverState *get_bdrv(int index)
4897 BlockDriverState *bs;
4900 bs = bs_table[index];
4901 } else if (index < 6) {
4902 bs = fd_table[index - 4];
4909 static void read_passwords(void)
4911 BlockDriverState *bs;
4915 for(i = 0; i < 6; i++) {
4917 if (bs && bdrv_is_encrypted(bs)) {
4918 term_printf("%s is encrypted.\n", bdrv_get_device_name(bs));
4919 for(j = 0; j < 3; j++) {
4920 monitor_readline("Password: ",
4921 1, password, sizeof(password));
4922 if (bdrv_set_key(bs, password) == 0)
4924 term_printf("invalid password\n");
4930 /* XXX: currently we cannot use simultaneously different CPUs */
4931 void register_machines(void)
4933 #if defined(TARGET_I386)
4934 qemu_register_machine(&pc_machine);
4935 qemu_register_machine(&isapc_machine);
4936 #elif defined(TARGET_PPC)
4937 qemu_register_machine(&heathrow_machine);
4938 qemu_register_machine(&core99_machine);
4939 qemu_register_machine(&prep_machine);
4940 #elif defined(TARGET_MIPS)
4941 qemu_register_machine(&mips_machine);
4942 #elif defined(TARGET_SPARC)
4943 #ifdef TARGET_SPARC64
4944 qemu_register_machine(&sun4u_machine);
4946 qemu_register_machine(&sun4m_machine);
4948 #elif defined(TARGET_ARM)
4949 qemu_register_machine(&integratorcp926_machine);
4950 qemu_register_machine(&integratorcp1026_machine);
4951 qemu_register_machine(&versatilepb_machine);
4952 qemu_register_machine(&versatileab_machine);
4953 #elif defined(TARGET_SH4)
4954 qemu_register_machine(&shix_machine);
4956 #error unsupported CPU
4961 struct soundhw soundhw[] = {
4968 { .init_isa = pcspk_audio_init }
4973 "Creative Sound Blaster 16",
4976 { .init_isa = SB16_init }
4983 "Yamaha YMF262 (OPL3)",
4985 "Yamaha YM3812 (OPL2)",
4989 { .init_isa = Adlib_init }
4996 "Gravis Ultrasound GF1",
4999 { .init_isa = GUS_init }
5005 "ENSONIQ AudioPCI ES1370",
5008 { .init_pci = es1370_init }
5011 { NULL, NULL, 0, 0, { NULL } }
5014 static void select_soundhw (const char *optarg)
5018 if (*optarg == '?') {
5021 printf ("Valid sound card names (comma separated):\n");
5022 for (c = soundhw; c->name; ++c) {
5023 printf ("%-11s %s\n", c->name, c->descr);
5025 printf ("\n-soundhw all will enable all of the above\n");
5026 exit (*optarg != '?');
5034 if (!strcmp (optarg, "all")) {
5035 for (c = soundhw; c->name; ++c) {
5043 e = strchr (p, ',');
5044 l = !e ? strlen (p) : (size_t) (e - p);
5046 for (c = soundhw; c->name; ++c) {
5047 if (!strncmp (c->name, p, l)) {
5056 "Unknown sound card name (too big to show)\n");
5059 fprintf (stderr, "Unknown sound card name `%.*s'\n",
5064 p += l + (e != NULL);
5068 goto show_valid_cards;
5073 #define MAX_NET_CLIENTS 32
5075 int main(int argc, char **argv)
5077 #ifdef CONFIG_GDBSTUB
5078 int use_gdbstub, gdbstub_port;
5081 int snapshot, linux_boot;
5082 const char *initrd_filename;
5083 const char *hd_filename[MAX_DISKS], *fd_filename[MAX_FD];
5084 const char *kernel_filename, *kernel_cmdline;
5085 DisplayState *ds = &display_state;
5086 int cyls, heads, secs, translation;
5087 int start_emulation = 1;
5088 char net_clients[MAX_NET_CLIENTS][256];
5091 const char *r, *optarg;
5092 CharDriverState *monitor_hd;
5093 char monitor_device[128];
5094 char serial_devices[MAX_SERIAL_PORTS][128];
5095 int serial_device_index;
5096 char parallel_devices[MAX_PARALLEL_PORTS][128];
5097 int parallel_device_index;
5098 const char *loadvm = NULL;
5099 QEMUMachine *machine;
5100 char usb_devices[MAX_USB_CMDLINE][128];
5101 int usb_devices_index;
5103 LIST_INIT (&vm_change_state_head);
5104 #if !defined(CONFIG_SOFTMMU)
5105 /* we never want that malloc() uses mmap() */
5106 mallopt(M_MMAP_THRESHOLD, 4096 * 1024);
5108 register_machines();
5109 machine = first_machine;
5110 initrd_filename = NULL;
5111 for(i = 0; i < MAX_FD; i++)
5112 fd_filename[i] = NULL;
5113 for(i = 0; i < MAX_DISKS; i++)
5114 hd_filename[i] = NULL;
5115 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5116 vga_ram_size = VGA_RAM_SIZE;
5117 bios_size = BIOS_SIZE;
5118 #ifdef CONFIG_GDBSTUB
5120 gdbstub_port = DEFAULT_GDBSTUB_PORT;
5124 kernel_filename = NULL;
5125 kernel_cmdline = "";
5131 cyls = heads = secs = 0;
5132 translation = BIOS_ATA_TRANSLATION_AUTO;
5133 pstrcpy(monitor_device, sizeof(monitor_device), "vc");
5135 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
5136 for(i = 1; i < MAX_SERIAL_PORTS; i++)
5137 serial_devices[i][0] = '\0';
5138 serial_device_index = 0;
5140 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
5141 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
5142 parallel_devices[i][0] = '\0';
5143 parallel_device_index = 0;
5145 usb_devices_index = 0;
5150 /* default mac address of the first network interface */
5158 hd_filename[0] = argv[optind++];
5160 const QEMUOption *popt;
5163 popt = qemu_options;
5166 fprintf(stderr, "%s: invalid option -- '%s'\n",
5170 if (!strcmp(popt->name, r + 1))
5174 if (popt->flags & HAS_ARG) {
5175 if (optind >= argc) {
5176 fprintf(stderr, "%s: option '%s' requires an argument\n",
5180 optarg = argv[optind++];
5185 switch(popt->index) {
5187 machine = find_machine(optarg);
5190 printf("Supported machines are:\n");
5191 for(m = first_machine; m != NULL; m = m->next) {
5192 printf("%-10s %s%s\n",
5194 m == first_machine ? " (default)" : "");
5199 case QEMU_OPTION_initrd:
5200 initrd_filename = optarg;
5202 case QEMU_OPTION_hda:
5203 case QEMU_OPTION_hdb:
5204 case QEMU_OPTION_hdc:
5205 case QEMU_OPTION_hdd:
5208 hd_index = popt->index - QEMU_OPTION_hda;
5209 hd_filename[hd_index] = optarg;
5210 if (hd_index == cdrom_index)
5214 case QEMU_OPTION_snapshot:
5217 case QEMU_OPTION_hdachs:
5221 cyls = strtol(p, (char **)&p, 0);
5222 if (cyls < 1 || cyls > 16383)
5227 heads = strtol(p, (char **)&p, 0);
5228 if (heads < 1 || heads > 16)
5233 secs = strtol(p, (char **)&p, 0);
5234 if (secs < 1 || secs > 63)
5238 if (!strcmp(p, "none"))
5239 translation = BIOS_ATA_TRANSLATION_NONE;
5240 else if (!strcmp(p, "lba"))
5241 translation = BIOS_ATA_TRANSLATION_LBA;
5242 else if (!strcmp(p, "auto"))
5243 translation = BIOS_ATA_TRANSLATION_AUTO;
5246 } else if (*p != '\0') {
5248 fprintf(stderr, "qemu: invalid physical CHS format\n");
5253 case QEMU_OPTION_nographic:
5254 pstrcpy(monitor_device, sizeof(monitor_device), "stdio");
5255 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "stdio");
5258 case QEMU_OPTION_kernel:
5259 kernel_filename = optarg;
5261 case QEMU_OPTION_append:
5262 kernel_cmdline = optarg;
5264 case QEMU_OPTION_cdrom:
5265 if (cdrom_index >= 0) {
5266 hd_filename[cdrom_index] = optarg;
5269 case QEMU_OPTION_boot:
5270 boot_device = optarg[0];
5271 if (boot_device != 'a' &&
5274 boot_device != 'n' &&
5276 boot_device != 'c' && boot_device != 'd') {
5277 fprintf(stderr, "qemu: invalid boot device '%c'\n", boot_device);
5281 case QEMU_OPTION_fda:
5282 fd_filename[0] = optarg;
5284 case QEMU_OPTION_fdb:
5285 fd_filename[1] = optarg;
5287 case QEMU_OPTION_no_code_copy:
5288 code_copy_enabled = 0;
5290 case QEMU_OPTION_net:
5291 if (nb_net_clients >= MAX_NET_CLIENTS) {
5292 fprintf(stderr, "qemu: too many network clients\n");
5295 pstrcpy(net_clients[nb_net_clients],
5296 sizeof(net_clients[0]),
5301 case QEMU_OPTION_tftp:
5302 tftp_prefix = optarg;
5305 case QEMU_OPTION_smb:
5306 net_slirp_smb(optarg);
5309 case QEMU_OPTION_redir:
5310 net_slirp_redir(optarg);
5314 case QEMU_OPTION_audio_help:
5318 case QEMU_OPTION_soundhw:
5319 select_soundhw (optarg);
5326 ram_size = atoi(optarg) * 1024 * 1024;
5329 if (ram_size > PHYS_RAM_MAX_SIZE) {
5330 fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
5331 PHYS_RAM_MAX_SIZE / (1024 * 1024));
5340 mask = cpu_str_to_log_mask(optarg);
5342 printf("Log items (comma separated):\n");
5343 for(item = cpu_log_items; item->mask != 0; item++) {
5344 printf("%-10s %s\n", item->name, item->help);
5351 #ifdef CONFIG_GDBSTUB
5356 gdbstub_port = atoi(optarg);
5363 start_emulation = 0;
5366 keyboard_layout = optarg;
5368 case QEMU_OPTION_localtime:
5371 case QEMU_OPTION_cirrusvga:
5372 cirrus_vga_enabled = 1;
5374 case QEMU_OPTION_std_vga:
5375 cirrus_vga_enabled = 0;
5382 w = strtol(p, (char **)&p, 10);
5385 fprintf(stderr, "qemu: invalid resolution or depth\n");
5391 h = strtol(p, (char **)&p, 10);
5396 depth = strtol(p, (char **)&p, 10);
5397 if (depth != 8 && depth != 15 && depth != 16 &&
5398 depth != 24 && depth != 32)
5400 } else if (*p == '\0') {
5401 depth = graphic_depth;
5408 graphic_depth = depth;
5411 case QEMU_OPTION_monitor:
5412 pstrcpy(monitor_device, sizeof(monitor_device), optarg);
5414 case QEMU_OPTION_serial:
5415 if (serial_device_index >= MAX_SERIAL_PORTS) {
5416 fprintf(stderr, "qemu: too many serial ports\n");
5419 pstrcpy(serial_devices[serial_device_index],
5420 sizeof(serial_devices[0]), optarg);
5421 serial_device_index++;
5423 case QEMU_OPTION_parallel:
5424 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
5425 fprintf(stderr, "qemu: too many parallel ports\n");
5428 pstrcpy(parallel_devices[parallel_device_index],
5429 sizeof(parallel_devices[0]), optarg);
5430 parallel_device_index++;
5432 case QEMU_OPTION_loadvm:
5435 case QEMU_OPTION_full_screen:
5438 case QEMU_OPTION_pidfile:
5439 create_pidfile(optarg);
5442 case QEMU_OPTION_win2k_hack:
5443 win2k_install_hack = 1;
5447 case QEMU_OPTION_no_kqemu:
5450 case QEMU_OPTION_kernel_kqemu:
5454 case QEMU_OPTION_usb:
5457 case QEMU_OPTION_usbdevice:
5459 if (usb_devices_index >= MAX_USB_CMDLINE) {
5460 fprintf(stderr, "Too many USB devices\n");
5463 pstrcpy(usb_devices[usb_devices_index],
5464 sizeof(usb_devices[usb_devices_index]),
5466 usb_devices_index++;
5468 case QEMU_OPTION_smp:
5469 smp_cpus = atoi(optarg);
5470 if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
5471 fprintf(stderr, "Invalid number of CPUs\n");
5475 case QEMU_OPTION_vnc:
5476 vnc_display = atoi(optarg);
5477 if (vnc_display < 0) {
5478 fprintf(stderr, "Invalid VNC display\n");
5482 case QEMU_OPTION_no_acpi:
5493 linux_boot = (kernel_filename != NULL);
5496 hd_filename[0] == '\0' &&
5497 (cdrom_index >= 0 && hd_filename[cdrom_index] == '\0') &&
5498 fd_filename[0] == '\0')
5501 /* boot to cd by default if no hard disk */
5502 if (hd_filename[0] == '\0' && boot_device == 'c') {
5503 if (fd_filename[0] != '\0')
5509 #if !defined(CONFIG_SOFTMMU)
5510 /* must avoid mmap() usage of glibc by setting a buffer "by hand" */
5512 static uint8_t stdout_buf[4096];
5513 setvbuf(stdout, stdout_buf, _IOLBF, sizeof(stdout_buf));
5516 setvbuf(stdout, NULL, _IOLBF, 0);
5523 /* init network clients */
5524 if (nb_net_clients == 0) {
5525 /* if no clients, we use a default config */
5526 pstrcpy(net_clients[0], sizeof(net_clients[0]),
5528 pstrcpy(net_clients[1], sizeof(net_clients[0]),
5533 for(i = 0;i < nb_net_clients; i++) {
5534 if (net_client_init(net_clients[i]) < 0)
5538 /* init the memory */
5539 phys_ram_size = ram_size + vga_ram_size + bios_size;
5541 #ifdef CONFIG_SOFTMMU
5542 phys_ram_base = qemu_vmalloc(phys_ram_size);
5543 if (!phys_ram_base) {
5544 fprintf(stderr, "Could not allocate physical memory\n");
5548 /* as we must map the same page at several addresses, we must use
5553 tmpdir = getenv("QEMU_TMPDIR");
5556 snprintf(phys_ram_file, sizeof(phys_ram_file), "%s/vlXXXXXX", tmpdir);
5557 if (mkstemp(phys_ram_file) < 0) {
5558 fprintf(stderr, "Could not create temporary memory file '%s'\n",
5562 phys_ram_fd = open(phys_ram_file, O_CREAT | O_TRUNC | O_RDWR, 0600);
5563 if (phys_ram_fd < 0) {
5564 fprintf(stderr, "Could not open temporary memory file '%s'\n",
5568 ftruncate(phys_ram_fd, phys_ram_size);
5569 unlink(phys_ram_file);
5570 phys_ram_base = mmap(get_mmap_addr(phys_ram_size),
5572 PROT_WRITE | PROT_READ, MAP_SHARED | MAP_FIXED,
5574 if (phys_ram_base == MAP_FAILED) {
5575 fprintf(stderr, "Could not map physical memory\n");
5581 /* we always create the cdrom drive, even if no disk is there */
5583 if (cdrom_index >= 0) {
5584 bs_table[cdrom_index] = bdrv_new("cdrom");
5585 bdrv_set_type_hint(bs_table[cdrom_index], BDRV_TYPE_CDROM);
5588 /* open the virtual block devices */
5589 for(i = 0; i < MAX_DISKS; i++) {
5590 if (hd_filename[i]) {
5593 snprintf(buf, sizeof(buf), "hd%c", i + 'a');
5594 bs_table[i] = bdrv_new(buf);
5596 if (bdrv_open(bs_table[i], hd_filename[i], snapshot) < 0) {
5597 fprintf(stderr, "qemu: could not open hard disk image '%s'\n",
5601 if (i == 0 && cyls != 0) {
5602 bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
5603 bdrv_set_translation_hint(bs_table[i], translation);
5608 /* we always create at least one floppy disk */
5609 fd_table[0] = bdrv_new("fda");
5610 bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
5612 for(i = 0; i < MAX_FD; i++) {
5613 if (fd_filename[i]) {
5616 snprintf(buf, sizeof(buf), "fd%c", i + 'a');
5617 fd_table[i] = bdrv_new(buf);
5618 bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
5620 if (fd_filename[i] != '\0') {
5621 if (bdrv_open(fd_table[i], fd_filename[i], snapshot) < 0) {
5622 fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
5630 register_savevm("timer", 0, 1, timer_save, timer_load, NULL);
5631 register_savevm("ram", 0, 1, ram_save, ram_load, NULL);
5634 cpu_calibrate_ticks();
5638 dumb_display_init(ds);
5639 } else if (vnc_display != -1) {
5640 vnc_display_init(ds, vnc_display);
5642 #if defined(CONFIG_SDL)
5643 sdl_display_init(ds, full_screen);
5644 #elif defined(CONFIG_COCOA)
5645 cocoa_display_init(ds, full_screen);
5647 dumb_display_init(ds);
5651 monitor_hd = qemu_chr_open(monitor_device);
5653 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
5656 monitor_init(monitor_hd, !nographic);
5658 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5659 if (serial_devices[i][0] != '\0') {
5660 serial_hds[i] = qemu_chr_open(serial_devices[i]);
5661 if (!serial_hds[i]) {
5662 fprintf(stderr, "qemu: could not open serial device '%s'\n",
5666 if (!strcmp(serial_devices[i], "vc"))
5667 qemu_chr_printf(serial_hds[i], "serial%d console\n", i);
5671 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5672 if (parallel_devices[i][0] != '\0') {
5673 parallel_hds[i] = qemu_chr_open(parallel_devices[i]);
5674 if (!parallel_hds[i]) {
5675 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
5676 parallel_devices[i]);
5679 if (!strcmp(parallel_devices[i], "vc"))
5680 qemu_chr_printf(parallel_hds[i], "parallel%d console\n", i);
5684 /* setup cpu signal handlers for MMU / self modifying code handling */
5685 #if !defined(CONFIG_SOFTMMU)
5687 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
5690 signal_stack = memalign(16, SIGNAL_STACK_SIZE);
5691 stk.ss_sp = signal_stack;
5692 stk.ss_size = SIGNAL_STACK_SIZE;
5695 if (sigaltstack(&stk, NULL) < 0) {
5696 perror("sigaltstack");
5702 struct sigaction act;
5704 sigfillset(&act.sa_mask);
5705 act.sa_flags = SA_SIGINFO;
5706 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
5707 act.sa_flags |= SA_ONSTACK;
5709 act.sa_sigaction = host_segv_handler;
5710 sigaction(SIGSEGV, &act, NULL);
5711 sigaction(SIGBUS, &act, NULL);
5712 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
5713 sigaction(SIGFPE, &act, NULL);
5720 struct sigaction act;
5721 sigfillset(&act.sa_mask);
5723 act.sa_handler = SIG_IGN;
5724 sigaction(SIGPIPE, &act, NULL);
5729 machine->init(ram_size, vga_ram_size, boot_device,
5730 ds, fd_filename, snapshot,
5731 kernel_filename, kernel_cmdline, initrd_filename);
5733 /* init USB devices */
5735 for(i = 0; i < usb_devices_index; i++) {
5736 if (usb_device_add(usb_devices[i]) < 0) {
5737 fprintf(stderr, "Warning: could not add USB device %s\n",
5743 gui_timer = qemu_new_timer(rt_clock, gui_update, NULL);
5744 qemu_mod_timer(gui_timer, qemu_get_clock(rt_clock));
5746 #ifdef CONFIG_GDBSTUB
5748 if (gdbserver_start(gdbstub_port) < 0) {
5749 fprintf(stderr, "Could not open gdbserver socket on port %d\n",
5753 printf("Waiting gdb connection on port %d\n", gdbstub_port);
5758 qemu_loadvm(loadvm);
5761 /* XXX: simplify init */
5763 if (start_emulation) {