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 /* XXX: use a two level table to limit memory usage */
110 #define MAX_IOPORTS 65536
112 const char *bios_dir = CONFIG_QEMU_SHAREDIR;
113 char phys_ram_file[1024];
114 void *ioport_opaque[MAX_IOPORTS];
115 IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
116 IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
117 BlockDriverState *bs_table[MAX_DISKS], *fd_table[MAX_FD];
120 static DisplayState display_state;
122 const char* keyboard_layout = NULL;
123 int64_t ticks_per_sec;
124 int boot_device = 'c';
126 int pit_min_timer_count = 0;
128 NICInfo nd_table[MAX_NICS];
129 QEMUTimer *gui_timer;
132 int cirrus_vga_enabled = 1;
134 int graphic_width = 1024;
135 int graphic_height = 768;
137 int graphic_width = 800;
138 int graphic_height = 600;
140 int graphic_depth = 15;
142 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
143 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
145 int win2k_install_hack = 0;
148 USBPort *vm_usb_ports[MAX_VM_USB_PORTS];
149 USBDevice *vm_usb_hub;
150 static VLANState *first_vlan;
152 int vnc_display = -1;
153 #if defined(TARGET_SPARC)
155 #elif defined(TARGET_I386)
161 /***********************************************************/
162 /* x86 ISA bus support */
164 target_phys_addr_t isa_mem_base = 0;
167 uint32_t default_ioport_readb(void *opaque, uint32_t address)
169 #ifdef DEBUG_UNUSED_IOPORT
170 fprintf(stderr, "inb: port=0x%04x\n", address);
175 void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
177 #ifdef DEBUG_UNUSED_IOPORT
178 fprintf(stderr, "outb: port=0x%04x data=0x%02x\n", address, data);
182 /* default is to make two byte accesses */
183 uint32_t default_ioport_readw(void *opaque, uint32_t address)
186 data = ioport_read_table[0][address](ioport_opaque[address], address);
187 address = (address + 1) & (MAX_IOPORTS - 1);
188 data |= ioport_read_table[0][address](ioport_opaque[address], address) << 8;
192 void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
194 ioport_write_table[0][address](ioport_opaque[address], address, data & 0xff);
195 address = (address + 1) & (MAX_IOPORTS - 1);
196 ioport_write_table[0][address](ioport_opaque[address], address, (data >> 8) & 0xff);
199 uint32_t default_ioport_readl(void *opaque, uint32_t address)
201 #ifdef DEBUG_UNUSED_IOPORT
202 fprintf(stderr, "inl: port=0x%04x\n", address);
207 void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
209 #ifdef DEBUG_UNUSED_IOPORT
210 fprintf(stderr, "outl: port=0x%04x data=0x%02x\n", address, data);
214 void init_ioports(void)
218 for(i = 0; i < MAX_IOPORTS; i++) {
219 ioport_read_table[0][i] = default_ioport_readb;
220 ioport_write_table[0][i] = default_ioport_writeb;
221 ioport_read_table[1][i] = default_ioport_readw;
222 ioport_write_table[1][i] = default_ioport_writew;
223 ioport_read_table[2][i] = default_ioport_readl;
224 ioport_write_table[2][i] = default_ioport_writel;
228 /* size is the word size in byte */
229 int register_ioport_read(int start, int length, int size,
230 IOPortReadFunc *func, void *opaque)
236 } else if (size == 2) {
238 } else if (size == 4) {
241 hw_error("register_ioport_read: invalid size");
244 for(i = start; i < start + length; i += size) {
245 ioport_read_table[bsize][i] = func;
246 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
247 hw_error("register_ioport_read: invalid opaque");
248 ioport_opaque[i] = opaque;
253 /* size is the word size in byte */
254 int register_ioport_write(int start, int length, int size,
255 IOPortWriteFunc *func, void *opaque)
261 } else if (size == 2) {
263 } else if (size == 4) {
266 hw_error("register_ioport_write: invalid size");
269 for(i = start; i < start + length; i += size) {
270 ioport_write_table[bsize][i] = func;
271 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
272 hw_error("register_ioport_read: invalid opaque");
273 ioport_opaque[i] = opaque;
278 void isa_unassign_ioport(int start, int length)
282 for(i = start; i < start + length; i++) {
283 ioport_read_table[0][i] = default_ioport_readb;
284 ioport_read_table[1][i] = default_ioport_readw;
285 ioport_read_table[2][i] = default_ioport_readl;
287 ioport_write_table[0][i] = default_ioport_writeb;
288 ioport_write_table[1][i] = default_ioport_writew;
289 ioport_write_table[2][i] = default_ioport_writel;
293 /***********************************************************/
295 void pstrcpy(char *buf, int buf_size, const char *str)
305 if (c == 0 || q >= buf + buf_size - 1)
312 /* strcat and truncate. */
313 char *pstrcat(char *buf, int buf_size, const char *s)
318 pstrcpy(buf + len, buf_size - len, s);
322 int strstart(const char *str, const char *val, const char **ptr)
338 void cpu_outb(CPUState *env, int addr, int val)
341 if (loglevel & CPU_LOG_IOPORT)
342 fprintf(logfile, "outb: %04x %02x\n", addr, val);
344 ioport_write_table[0][addr](ioport_opaque[addr], addr, val);
347 env->last_io_time = cpu_get_time_fast();
351 void cpu_outw(CPUState *env, int addr, int val)
354 if (loglevel & CPU_LOG_IOPORT)
355 fprintf(logfile, "outw: %04x %04x\n", addr, val);
357 ioport_write_table[1][addr](ioport_opaque[addr], addr, val);
360 env->last_io_time = cpu_get_time_fast();
364 void cpu_outl(CPUState *env, int addr, int val)
367 if (loglevel & CPU_LOG_IOPORT)
368 fprintf(logfile, "outl: %04x %08x\n", addr, val);
370 ioport_write_table[2][addr](ioport_opaque[addr], addr, val);
373 env->last_io_time = cpu_get_time_fast();
377 int cpu_inb(CPUState *env, int addr)
380 val = ioport_read_table[0][addr](ioport_opaque[addr], addr);
382 if (loglevel & CPU_LOG_IOPORT)
383 fprintf(logfile, "inb : %04x %02x\n", addr, val);
387 env->last_io_time = cpu_get_time_fast();
392 int cpu_inw(CPUState *env, int addr)
395 val = ioport_read_table[1][addr](ioport_opaque[addr], addr);
397 if (loglevel & CPU_LOG_IOPORT)
398 fprintf(logfile, "inw : %04x %04x\n", addr, val);
402 env->last_io_time = cpu_get_time_fast();
407 int cpu_inl(CPUState *env, int addr)
410 val = ioport_read_table[2][addr](ioport_opaque[addr], addr);
412 if (loglevel & CPU_LOG_IOPORT)
413 fprintf(logfile, "inl : %04x %08x\n", addr, val);
417 env->last_io_time = cpu_get_time_fast();
422 /***********************************************************/
423 void hw_error(const char *fmt, ...)
429 fprintf(stderr, "qemu: hardware error: ");
430 vfprintf(stderr, fmt, ap);
431 fprintf(stderr, "\n");
432 for(env = first_cpu; env != NULL; env = env->next_cpu) {
433 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
435 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
437 cpu_dump_state(env, stderr, fprintf, 0);
444 /***********************************************************/
447 static QEMUPutKBDEvent *qemu_put_kbd_event;
448 static void *qemu_put_kbd_event_opaque;
449 static QEMUPutMouseEvent *qemu_put_mouse_event;
450 static void *qemu_put_mouse_event_opaque;
451 static int qemu_put_mouse_event_absolute;
453 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
455 qemu_put_kbd_event_opaque = opaque;
456 qemu_put_kbd_event = func;
459 void qemu_add_mouse_event_handler(QEMUPutMouseEvent *func, void *opaque, int absolute)
461 qemu_put_mouse_event_opaque = opaque;
462 qemu_put_mouse_event = func;
463 qemu_put_mouse_event_absolute = absolute;
466 void kbd_put_keycode(int keycode)
468 if (qemu_put_kbd_event) {
469 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
473 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
475 if (qemu_put_mouse_event) {
476 qemu_put_mouse_event(qemu_put_mouse_event_opaque,
477 dx, dy, dz, buttons_state);
481 int kbd_mouse_is_absolute(void)
483 return qemu_put_mouse_event_absolute;
486 /***********************************************************/
489 #if defined(__powerpc__)
491 static inline uint32_t get_tbl(void)
494 asm volatile("mftb %0" : "=r" (tbl));
498 static inline uint32_t get_tbu(void)
501 asm volatile("mftbu %0" : "=r" (tbl));
505 int64_t cpu_get_real_ticks(void)
508 /* NOTE: we test if wrapping has occurred */
514 return ((int64_t)h << 32) | l;
517 #elif defined(__i386__)
519 int64_t cpu_get_real_ticks(void)
523 QueryPerformanceCounter(&ti);
527 asm volatile ("rdtsc" : "=A" (val));
532 #elif defined(__x86_64__)
534 int64_t cpu_get_real_ticks(void)
538 asm volatile("rdtsc" : "=a" (low), "=d" (high));
545 #elif defined(__ia64)
547 int64_t cpu_get_real_ticks(void)
550 asm volatile ("mov %0 = ar.itc" : "=r"(val) :: "memory");
554 #elif defined(__s390__)
556 int64_t cpu_get_real_ticks(void)
559 asm volatile("stck 0(%1)" : "=m" (val) : "a" (&val) : "cc");
564 #error unsupported CPU
567 static int64_t cpu_ticks_prev;
568 static int64_t cpu_ticks_offset;
569 static int cpu_ticks_enabled;
571 static inline int64_t cpu_get_ticks(void)
573 if (!cpu_ticks_enabled) {
574 return cpu_ticks_offset;
577 ticks = cpu_get_real_ticks();
578 if (cpu_ticks_prev > ticks) {
579 /* Note: non increasing ticks may happen if the host uses
581 cpu_ticks_offset += cpu_ticks_prev - ticks;
583 cpu_ticks_prev = ticks;
584 return ticks + cpu_ticks_offset;
588 /* enable cpu_get_ticks() */
589 void cpu_enable_ticks(void)
591 if (!cpu_ticks_enabled) {
592 cpu_ticks_offset -= cpu_get_real_ticks();
593 cpu_ticks_enabled = 1;
597 /* disable cpu_get_ticks() : the clock is stopped. You must not call
598 cpu_get_ticks() after that. */
599 void cpu_disable_ticks(void)
601 if (cpu_ticks_enabled) {
602 cpu_ticks_offset = cpu_get_ticks();
603 cpu_ticks_enabled = 0;
608 void cpu_calibrate_ticks(void)
613 ret = QueryPerformanceFrequency(&freq);
615 fprintf(stderr, "Could not calibrate ticks\n");
618 ticks_per_sec = freq.QuadPart;
622 static int64_t get_clock(void)
625 gettimeofday(&tv, NULL);
626 return tv.tv_sec * 1000000LL + tv.tv_usec;
629 void cpu_calibrate_ticks(void)
634 ticks = cpu_get_real_ticks();
636 usec = get_clock() - usec;
637 ticks = cpu_get_real_ticks() - ticks;
638 ticks_per_sec = (ticks * 1000000LL + (usec >> 1)) / usec;
642 /* compute with 96 bit intermediate result: (a*b)/c */
643 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
648 #ifdef WORDS_BIGENDIAN
658 rl = (uint64_t)u.l.low * (uint64_t)b;
659 rh = (uint64_t)u.l.high * (uint64_t)b;
662 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
666 #define QEMU_TIMER_REALTIME 0
667 #define QEMU_TIMER_VIRTUAL 1
671 /* XXX: add frequency */
679 struct QEMUTimer *next;
685 static QEMUTimer *active_timers[2];
687 static MMRESULT timerID;
688 static HANDLE host_alarm = NULL;
689 static unsigned int period = 1;
691 /* frequency of the times() clock tick */
692 static int timer_freq;
695 QEMUClock *qemu_new_clock(int type)
698 clock = qemu_mallocz(sizeof(QEMUClock));
705 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
709 ts = qemu_mallocz(sizeof(QEMUTimer));
716 void qemu_free_timer(QEMUTimer *ts)
721 /* stop a timer, but do not dealloc it */
722 void qemu_del_timer(QEMUTimer *ts)
726 /* NOTE: this code must be signal safe because
727 qemu_timer_expired() can be called from a signal. */
728 pt = &active_timers[ts->clock->type];
741 /* modify the current timer so that it will be fired when current_time
742 >= expire_time. The corresponding callback will be called. */
743 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
749 /* add the timer in the sorted list */
750 /* NOTE: this code must be signal safe because
751 qemu_timer_expired() can be called from a signal. */
752 pt = &active_timers[ts->clock->type];
757 if (t->expire_time > expire_time)
761 ts->expire_time = expire_time;
766 int qemu_timer_pending(QEMUTimer *ts)
769 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
776 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
780 return (timer_head->expire_time <= current_time);
783 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
789 if (!ts || ts->expire_time > current_time)
791 /* remove timer from the list before calling the callback */
792 *ptimer_head = ts->next;
795 /* run the callback (the timer list can be modified) */
800 int64_t qemu_get_clock(QEMUClock *clock)
802 switch(clock->type) {
803 case QEMU_TIMER_REALTIME:
805 return GetTickCount();
810 /* Note that using gettimeofday() is not a good solution
811 for timers because its value change when the date is
813 if (timer_freq == 100) {
814 return times(&tp) * 10;
816 return ((int64_t)times(&tp) * 1000) / timer_freq;
821 case QEMU_TIMER_VIRTUAL:
822 return cpu_get_ticks();
827 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
829 uint64_t expire_time;
831 if (qemu_timer_pending(ts)) {
832 expire_time = ts->expire_time;
836 qemu_put_be64(f, expire_time);
839 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
841 uint64_t expire_time;
843 expire_time = qemu_get_be64(f);
844 if (expire_time != -1) {
845 qemu_mod_timer(ts, expire_time);
851 static void timer_save(QEMUFile *f, void *opaque)
853 if (cpu_ticks_enabled) {
854 hw_error("cannot save state if virtual timers are running");
856 qemu_put_be64s(f, &cpu_ticks_offset);
857 qemu_put_be64s(f, &ticks_per_sec);
860 static int timer_load(QEMUFile *f, void *opaque, int version_id)
864 if (cpu_ticks_enabled) {
867 qemu_get_be64s(f, &cpu_ticks_offset);
868 qemu_get_be64s(f, &ticks_per_sec);
873 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
874 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
876 static void host_alarm_handler(int host_signum)
880 #define DISP_FREQ 1000
882 static int64_t delta_min = INT64_MAX;
883 static int64_t delta_max, delta_cum, last_clock, delta, ti;
885 ti = qemu_get_clock(vm_clock);
886 if (last_clock != 0) {
887 delta = ti - last_clock;
888 if (delta < delta_min)
890 if (delta > delta_max)
893 if (++count == DISP_FREQ) {
894 printf("timer: min=%lld us max=%lld us avg=%lld us avg_freq=%0.3f Hz\n",
895 muldiv64(delta_min, 1000000, ticks_per_sec),
896 muldiv64(delta_max, 1000000, ticks_per_sec),
897 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
898 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
900 delta_min = INT64_MAX;
908 if (qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
909 qemu_get_clock(vm_clock)) ||
910 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
911 qemu_get_clock(rt_clock))) {
913 SetEvent(host_alarm);
915 CPUState *env = cpu_single_env;
917 /* stop the currently executing cpu because a timer occured */
918 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
920 if (env->kqemu_enabled) {
921 kqemu_cpu_interrupt(env);
930 #if defined(__linux__)
932 #define RTC_FREQ 1024
936 static int start_rtc_timer(void)
938 rtc_fd = open("/dev/rtc", O_RDONLY);
941 if (ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
942 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
943 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
944 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
947 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
952 pit_min_timer_count = PIT_FREQ / RTC_FREQ;
958 static int start_rtc_timer(void)
963 #endif /* !defined(__linux__) */
965 #endif /* !defined(_WIN32) */
967 static void init_timers(void)
969 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
970 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
977 ZeroMemory(&tc, sizeof(TIMECAPS));
978 timeGetDevCaps(&tc, sizeof(TIMECAPS));
979 if (period < tc.wPeriodMin)
980 period = tc.wPeriodMin;
981 timeBeginPeriod(period);
982 timerID = timeSetEvent(1, // interval (ms)
983 period, // resolution
984 host_alarm_handler, // function
985 (DWORD)&count, // user parameter
986 TIME_PERIODIC | TIME_CALLBACK_FUNCTION);
988 perror("failed timer alarm");
991 host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
993 perror("failed CreateEvent");
996 ResetEvent(host_alarm);
998 pit_min_timer_count = ((uint64_t)10000 * PIT_FREQ) / 1000000;
1001 struct sigaction act;
1002 struct itimerval itv;
1004 /* get times() syscall frequency */
1005 timer_freq = sysconf(_SC_CLK_TCK);
1008 sigfillset(&act.sa_mask);
1010 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
1011 act.sa_flags |= SA_ONSTACK;
1013 act.sa_handler = host_alarm_handler;
1014 sigaction(SIGALRM, &act, NULL);
1016 itv.it_interval.tv_sec = 0;
1017 itv.it_interval.tv_usec = 999; /* for i386 kernel 2.6 to get 1 ms */
1018 itv.it_value.tv_sec = 0;
1019 itv.it_value.tv_usec = 10 * 1000;
1020 setitimer(ITIMER_REAL, &itv, NULL);
1021 /* we probe the tick duration of the kernel to inform the user if
1022 the emulated kernel requested a too high timer frequency */
1023 getitimer(ITIMER_REAL, &itv);
1025 #if defined(__linux__)
1026 if (itv.it_interval.tv_usec > 1000) {
1027 /* try to use /dev/rtc to have a faster timer */
1028 if (start_rtc_timer() < 0)
1030 /* disable itimer */
1031 itv.it_interval.tv_sec = 0;
1032 itv.it_interval.tv_usec = 0;
1033 itv.it_value.tv_sec = 0;
1034 itv.it_value.tv_usec = 0;
1035 setitimer(ITIMER_REAL, &itv, NULL);
1038 sigaction(SIGIO, &act, NULL);
1039 fcntl(rtc_fd, F_SETFL, O_ASYNC);
1040 fcntl(rtc_fd, F_SETOWN, getpid());
1042 #endif /* defined(__linux__) */
1045 pit_min_timer_count = ((uint64_t)itv.it_interval.tv_usec *
1046 PIT_FREQ) / 1000000;
1052 void quit_timers(void)
1055 timeKillEvent(timerID);
1056 timeEndPeriod(period);
1058 CloseHandle(host_alarm);
1064 /***********************************************************/
1065 /* character device */
1067 int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1069 return s->chr_write(s, buf, len);
1072 int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1076 return s->chr_ioctl(s, cmd, arg);
1079 void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1084 vsnprintf(buf, sizeof(buf), fmt, ap);
1085 qemu_chr_write(s, buf, strlen(buf));
1089 void qemu_chr_send_event(CharDriverState *s, int event)
1091 if (s->chr_send_event)
1092 s->chr_send_event(s, event);
1095 void qemu_chr_add_read_handler(CharDriverState *s,
1096 IOCanRWHandler *fd_can_read,
1097 IOReadHandler *fd_read, void *opaque)
1099 s->chr_add_read_handler(s, fd_can_read, fd_read, opaque);
1102 void qemu_chr_add_event_handler(CharDriverState *s, IOEventHandler *chr_event)
1104 s->chr_event = chr_event;
1107 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1112 static void null_chr_add_read_handler(CharDriverState *chr,
1113 IOCanRWHandler *fd_can_read,
1114 IOReadHandler *fd_read, void *opaque)
1118 CharDriverState *qemu_chr_open_null(void)
1120 CharDriverState *chr;
1122 chr = qemu_mallocz(sizeof(CharDriverState));
1125 chr->chr_write = null_chr_write;
1126 chr->chr_add_read_handler = null_chr_add_read_handler;
1132 static void socket_cleanup(void)
1137 static int socket_init(void)
1142 ret = WSAStartup(MAKEWORD(2,2), &Data);
1144 err = WSAGetLastError();
1145 fprintf(stderr, "WSAStartup: %d\n", err);
1148 atexit(socket_cleanup);
1152 static int send_all(int fd, const uint8_t *buf, int len1)
1158 ret = send(fd, buf, len, 0);
1161 errno = WSAGetLastError();
1162 if (errno != WSAEWOULDBLOCK) {
1165 } else if (ret == 0) {
1175 void socket_set_nonblock(int fd)
1177 unsigned long opt = 1;
1178 ioctlsocket(fd, FIONBIO, &opt);
1183 static int unix_write(int fd, const uint8_t *buf, int len1)
1189 ret = write(fd, buf, len);
1191 if (errno != EINTR && errno != EAGAIN)
1193 } else if (ret == 0) {
1203 static inline int send_all(int fd, const uint8_t *buf, int len1)
1205 return unix_write(fd, buf, len1);
1208 void socket_set_nonblock(int fd)
1210 fcntl(fd, F_SETFL, O_NONBLOCK);
1212 #endif /* !_WIN32 */
1218 IOCanRWHandler *fd_can_read;
1219 IOReadHandler *fd_read;
1224 #define STDIO_MAX_CLIENTS 2
1226 static int stdio_nb_clients;
1227 static CharDriverState *stdio_clients[STDIO_MAX_CLIENTS];
1229 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1231 FDCharDriver *s = chr->opaque;
1232 return unix_write(s->fd_out, buf, len);
1235 static int fd_chr_read_poll(void *opaque)
1237 CharDriverState *chr = opaque;
1238 FDCharDriver *s = chr->opaque;
1240 s->max_size = s->fd_can_read(s->fd_opaque);
1244 static void fd_chr_read(void *opaque)
1246 CharDriverState *chr = opaque;
1247 FDCharDriver *s = chr->opaque;
1252 if (len > s->max_size)
1256 size = read(s->fd_in, buf, len);
1258 s->fd_read(s->fd_opaque, buf, size);
1262 static void fd_chr_add_read_handler(CharDriverState *chr,
1263 IOCanRWHandler *fd_can_read,
1264 IOReadHandler *fd_read, void *opaque)
1266 FDCharDriver *s = chr->opaque;
1268 if (s->fd_in >= 0) {
1269 s->fd_can_read = fd_can_read;
1270 s->fd_read = fd_read;
1271 s->fd_opaque = opaque;
1272 if (nographic && s->fd_in == 0) {
1274 qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
1275 fd_chr_read, NULL, chr);
1280 /* open a character device to a unix fd */
1281 CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
1283 CharDriverState *chr;
1286 chr = qemu_mallocz(sizeof(CharDriverState));
1289 s = qemu_mallocz(sizeof(FDCharDriver));
1297 chr->chr_write = fd_chr_write;
1298 chr->chr_add_read_handler = fd_chr_add_read_handler;
1302 CharDriverState *qemu_chr_open_file_out(const char *file_out)
1306 fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666);
1309 return qemu_chr_open_fd(-1, fd_out);
1312 CharDriverState *qemu_chr_open_pipe(const char *filename)
1316 fd = open(filename, O_RDWR | O_BINARY);
1319 return qemu_chr_open_fd(fd, fd);
1323 /* for STDIO, we handle the case where several clients use it
1326 #define TERM_ESCAPE 0x01 /* ctrl-a is used for escape */
1328 #define TERM_FIFO_MAX_SIZE 1
1330 static int term_got_escape, client_index;
1331 static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
1334 void term_print_help(void)
1337 "C-a h print this help\n"
1338 "C-a x exit emulator\n"
1339 "C-a s save disk data back to file (if -snapshot)\n"
1340 "C-a b send break (magic sysrq)\n"
1341 "C-a c switch between console and monitor\n"
1342 "C-a C-a send C-a\n"
1346 /* called when a char is received */
1347 static void stdio_received_byte(int ch)
1349 if (term_got_escape) {
1350 term_got_escape = 0;
1361 for (i = 0; i < MAX_DISKS; i++) {
1363 bdrv_commit(bs_table[i]);
1368 if (client_index < stdio_nb_clients) {
1369 CharDriverState *chr;
1372 chr = stdio_clients[client_index];
1374 chr->chr_event(s->fd_opaque, CHR_EVENT_BREAK);
1379 if (client_index >= stdio_nb_clients)
1381 if (client_index == 0) {
1382 /* send a new line in the monitor to get the prompt */
1390 } else if (ch == TERM_ESCAPE) {
1391 term_got_escape = 1;
1394 if (client_index < stdio_nb_clients) {
1396 CharDriverState *chr;
1399 chr = stdio_clients[client_index];
1401 if (s->fd_can_read(s->fd_opaque) > 0) {
1403 s->fd_read(s->fd_opaque, buf, 1);
1404 } else if (term_fifo_size == 0) {
1405 term_fifo[term_fifo_size++] = ch;
1411 static int stdio_read_poll(void *opaque)
1413 CharDriverState *chr;
1416 if (client_index < stdio_nb_clients) {
1417 chr = stdio_clients[client_index];
1419 /* try to flush the queue if needed */
1420 if (term_fifo_size != 0 && s->fd_can_read(s->fd_opaque) > 0) {
1421 s->fd_read(s->fd_opaque, term_fifo, 1);
1424 /* see if we can absorb more chars */
1425 if (term_fifo_size == 0)
1434 static void stdio_read(void *opaque)
1439 size = read(0, buf, 1);
1441 stdio_received_byte(buf[0]);
1444 /* init terminal so that we can grab keys */
1445 static struct termios oldtty;
1446 static int old_fd0_flags;
1448 static void term_exit(void)
1450 tcsetattr (0, TCSANOW, &oldtty);
1451 fcntl(0, F_SETFL, old_fd0_flags);
1454 static void term_init(void)
1458 tcgetattr (0, &tty);
1460 old_fd0_flags = fcntl(0, F_GETFL);
1462 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1463 |INLCR|IGNCR|ICRNL|IXON);
1464 tty.c_oflag |= OPOST;
1465 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1466 /* if graphical mode, we allow Ctrl-C handling */
1468 tty.c_lflag &= ~ISIG;
1469 tty.c_cflag &= ~(CSIZE|PARENB);
1472 tty.c_cc[VTIME] = 0;
1474 tcsetattr (0, TCSANOW, &tty);
1478 fcntl(0, F_SETFL, O_NONBLOCK);
1481 CharDriverState *qemu_chr_open_stdio(void)
1483 CharDriverState *chr;
1486 if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
1488 chr = qemu_chr_open_fd(0, 1);
1489 if (stdio_nb_clients == 0)
1490 qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, NULL);
1491 client_index = stdio_nb_clients;
1493 if (stdio_nb_clients != 0)
1495 chr = qemu_chr_open_fd(0, 1);
1497 stdio_clients[stdio_nb_clients++] = chr;
1498 if (stdio_nb_clients == 1) {
1499 /* set the terminal in raw mode */
1505 #if defined(__linux__)
1506 CharDriverState *qemu_chr_open_pty(void)
1509 char slave_name[1024];
1510 int master_fd, slave_fd;
1512 /* Not satisfying */
1513 if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
1517 /* Disabling local echo and line-buffered output */
1518 tcgetattr (master_fd, &tty);
1519 tty.c_lflag &= ~(ECHO|ICANON|ISIG);
1521 tty.c_cc[VTIME] = 0;
1522 tcsetattr (master_fd, TCSAFLUSH, &tty);
1524 fprintf(stderr, "char device redirected to %s\n", slave_name);
1525 return qemu_chr_open_fd(master_fd, master_fd);
1528 static void tty_serial_init(int fd, int speed,
1529 int parity, int data_bits, int stop_bits)
1535 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1536 speed, parity, data_bits, stop_bits);
1538 tcgetattr (fd, &tty);
1580 cfsetispeed(&tty, spd);
1581 cfsetospeed(&tty, spd);
1583 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1584 |INLCR|IGNCR|ICRNL|IXON);
1585 tty.c_oflag |= OPOST;
1586 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1587 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS);
1608 tty.c_cflag |= PARENB;
1611 tty.c_cflag |= PARENB | PARODD;
1615 tcsetattr (fd, TCSANOW, &tty);
1618 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1620 FDCharDriver *s = chr->opaque;
1623 case CHR_IOCTL_SERIAL_SET_PARAMS:
1625 QEMUSerialSetParams *ssp = arg;
1626 tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
1627 ssp->data_bits, ssp->stop_bits);
1630 case CHR_IOCTL_SERIAL_SET_BREAK:
1632 int enable = *(int *)arg;
1634 tcsendbreak(s->fd_in, 1);
1643 CharDriverState *qemu_chr_open_tty(const char *filename)
1645 CharDriverState *chr;
1648 fd = open(filename, O_RDWR | O_NONBLOCK);
1651 fcntl(fd, F_SETFL, O_NONBLOCK);
1652 tty_serial_init(fd, 115200, 'N', 8, 1);
1653 chr = qemu_chr_open_fd(fd, fd);
1656 chr->chr_ioctl = tty_serial_ioctl;
1660 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1662 int fd = (int)chr->opaque;
1666 case CHR_IOCTL_PP_READ_DATA:
1667 if (ioctl(fd, PPRDATA, &b) < 0)
1669 *(uint8_t *)arg = b;
1671 case CHR_IOCTL_PP_WRITE_DATA:
1672 b = *(uint8_t *)arg;
1673 if (ioctl(fd, PPWDATA, &b) < 0)
1676 case CHR_IOCTL_PP_READ_CONTROL:
1677 if (ioctl(fd, PPRCONTROL, &b) < 0)
1679 *(uint8_t *)arg = b;
1681 case CHR_IOCTL_PP_WRITE_CONTROL:
1682 b = *(uint8_t *)arg;
1683 if (ioctl(fd, PPWCONTROL, &b) < 0)
1686 case CHR_IOCTL_PP_READ_STATUS:
1687 if (ioctl(fd, PPRSTATUS, &b) < 0)
1689 *(uint8_t *)arg = b;
1697 CharDriverState *qemu_chr_open_pp(const char *filename)
1699 CharDriverState *chr;
1702 fd = open(filename, O_RDWR);
1706 if (ioctl(fd, PPCLAIM) < 0) {
1711 chr = qemu_mallocz(sizeof(CharDriverState));
1716 chr->opaque = (void *)fd;
1717 chr->chr_write = null_chr_write;
1718 chr->chr_add_read_handler = null_chr_add_read_handler;
1719 chr->chr_ioctl = pp_ioctl;
1724 CharDriverState *qemu_chr_open_pty(void)
1730 #endif /* !defined(_WIN32) */
1734 IOCanRWHandler *fd_can_read;
1735 IOReadHandler *fd_read;
1738 HANDLE hcom, hrecv, hsend;
1739 OVERLAPPED orecv, osend;
1744 #define NSENDBUF 2048
1745 #define NRECVBUF 2048
1746 #define MAXCONNECT 1
1747 #define NTIMEOUT 5000
1749 static int win_chr_poll(void *opaque);
1750 static int win_chr_pipe_poll(void *opaque);
1752 static void win_chr_close2(WinCharState *s)
1755 CloseHandle(s->hsend);
1759 CloseHandle(s->hrecv);
1763 CloseHandle(s->hcom);
1767 qemu_del_polling_cb(win_chr_pipe_poll, s);
1769 qemu_del_polling_cb(win_chr_poll, s);
1772 static void win_chr_close(CharDriverState *chr)
1774 WinCharState *s = chr->opaque;
1778 static int win_chr_init(WinCharState *s, const char *filename)
1781 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
1786 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1788 fprintf(stderr, "Failed CreateEvent\n");
1791 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1793 fprintf(stderr, "Failed CreateEvent\n");
1797 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
1798 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
1799 if (s->hcom == INVALID_HANDLE_VALUE) {
1800 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
1805 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
1806 fprintf(stderr, "Failed SetupComm\n");
1810 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
1811 size = sizeof(COMMCONFIG);
1812 GetDefaultCommConfig(filename, &comcfg, &size);
1813 comcfg.dcb.DCBlength = sizeof(DCB);
1814 CommConfigDialog(filename, NULL, &comcfg);
1816 if (!SetCommState(s->hcom, &comcfg.dcb)) {
1817 fprintf(stderr, "Failed SetCommState\n");
1821 if (!SetCommMask(s->hcom, EV_ERR)) {
1822 fprintf(stderr, "Failed SetCommMask\n");
1826 cto.ReadIntervalTimeout = MAXDWORD;
1827 if (!SetCommTimeouts(s->hcom, &cto)) {
1828 fprintf(stderr, "Failed SetCommTimeouts\n");
1832 if (!ClearCommError(s->hcom, &err, &comstat)) {
1833 fprintf(stderr, "Failed ClearCommError\n");
1836 qemu_add_polling_cb(win_chr_poll, s);
1844 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
1846 WinCharState *s = chr->opaque;
1847 DWORD len, ret, size, err;
1850 ZeroMemory(&s->osend, sizeof(s->osend));
1851 s->osend.hEvent = s->hsend;
1854 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
1856 ret = WriteFile(s->hcom, buf, len, &size, NULL);
1858 err = GetLastError();
1859 if (err == ERROR_IO_PENDING) {
1860 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
1878 static int win_chr_read_poll(WinCharState *s)
1880 s->max_size = s->fd_can_read(s->win_opaque);
1884 static void win_chr_readfile(WinCharState *s)
1890 ZeroMemory(&s->orecv, sizeof(s->orecv));
1891 s->orecv.hEvent = s->hrecv;
1892 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
1894 err = GetLastError();
1895 if (err == ERROR_IO_PENDING) {
1896 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
1901 s->fd_read(s->win_opaque, buf, size);
1905 static void win_chr_read(WinCharState *s)
1907 if (s->len > s->max_size)
1908 s->len = s->max_size;
1912 win_chr_readfile(s);
1915 static int win_chr_poll(void *opaque)
1917 WinCharState *s = opaque;
1921 ClearCommError(s->hcom, &comerr, &status);
1922 if (status.cbInQue > 0) {
1923 s->len = status.cbInQue;
1924 win_chr_read_poll(s);
1931 static void win_chr_add_read_handler(CharDriverState *chr,
1932 IOCanRWHandler *fd_can_read,
1933 IOReadHandler *fd_read, void *opaque)
1935 WinCharState *s = chr->opaque;
1937 s->fd_can_read = fd_can_read;
1938 s->fd_read = fd_read;
1939 s->win_opaque = opaque;
1942 CharDriverState *qemu_chr_open_win(const char *filename)
1944 CharDriverState *chr;
1947 chr = qemu_mallocz(sizeof(CharDriverState));
1950 s = qemu_mallocz(sizeof(WinCharState));
1956 chr->chr_write = win_chr_write;
1957 chr->chr_add_read_handler = win_chr_add_read_handler;
1958 chr->chr_close = win_chr_close;
1960 if (win_chr_init(s, filename) < 0) {
1968 static int win_chr_pipe_poll(void *opaque)
1970 WinCharState *s = opaque;
1973 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
1976 win_chr_read_poll(s);
1983 static int win_chr_pipe_init(WinCharState *s, const char *filename)
1992 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1994 fprintf(stderr, "Failed CreateEvent\n");
1997 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1999 fprintf(stderr, "Failed CreateEvent\n");
2003 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
2004 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2005 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
2007 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2008 if (s->hcom == INVALID_HANDLE_VALUE) {
2009 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
2014 ZeroMemory(&ov, sizeof(ov));
2015 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2016 ret = ConnectNamedPipe(s->hcom, &ov);
2018 fprintf(stderr, "Failed ConnectNamedPipe\n");
2022 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2024 fprintf(stderr, "Failed GetOverlappedResult\n");
2026 CloseHandle(ov.hEvent);
2033 CloseHandle(ov.hEvent);
2036 qemu_add_polling_cb(win_chr_pipe_poll, s);
2045 CharDriverState *qemu_chr_open_win_pipe(const char *filename)
2047 CharDriverState *chr;
2050 chr = qemu_mallocz(sizeof(CharDriverState));
2053 s = qemu_mallocz(sizeof(WinCharState));
2059 chr->chr_write = win_chr_write;
2060 chr->chr_add_read_handler = win_chr_add_read_handler;
2061 chr->chr_close = win_chr_close;
2063 if (win_chr_pipe_init(s, filename) < 0) {
2071 CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
2073 CharDriverState *chr;
2076 chr = qemu_mallocz(sizeof(CharDriverState));
2079 s = qemu_mallocz(sizeof(WinCharState));
2086 chr->chr_write = win_chr_write;
2087 chr->chr_add_read_handler = win_chr_add_read_handler;
2091 CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
2095 fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
2096 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2097 if (fd_out == INVALID_HANDLE_VALUE)
2100 return qemu_chr_open_win_file(fd_out);
2104 CharDriverState *qemu_chr_open(const char *filename)
2108 if (!strcmp(filename, "vc")) {
2109 return text_console_init(&display_state);
2110 } else if (!strcmp(filename, "null")) {
2111 return qemu_chr_open_null();
2114 if (strstart(filename, "file:", &p)) {
2115 return qemu_chr_open_file_out(p);
2116 } else if (strstart(filename, "pipe:", &p)) {
2117 return qemu_chr_open_pipe(p);
2118 } else if (!strcmp(filename, "pty")) {
2119 return qemu_chr_open_pty();
2120 } else if (!strcmp(filename, "stdio")) {
2121 return qemu_chr_open_stdio();
2124 #if defined(__linux__)
2125 if (strstart(filename, "/dev/parport", NULL)) {
2126 return qemu_chr_open_pp(filename);
2128 if (strstart(filename, "/dev/", NULL)) {
2129 return qemu_chr_open_tty(filename);
2133 if (strstart(filename, "COM", NULL)) {
2134 return qemu_chr_open_win(filename);
2136 if (strstart(filename, "pipe:", &p)) {
2137 return qemu_chr_open_win_pipe(p);
2139 if (strstart(filename, "file:", &p)) {
2140 return qemu_chr_open_win_file_out(p);
2148 void qemu_chr_close(CharDriverState *chr)
2151 chr->chr_close(chr);
2154 /***********************************************************/
2155 /* network device redirectors */
2157 void hex_dump(FILE *f, const uint8_t *buf, int size)
2161 for(i=0;i<size;i+=16) {
2165 fprintf(f, "%08x ", i);
2168 fprintf(f, " %02x", buf[i+j]);
2173 for(j=0;j<len;j++) {
2175 if (c < ' ' || c > '~')
2177 fprintf(f, "%c", c);
2183 static int parse_macaddr(uint8_t *macaddr, const char *p)
2186 for(i = 0; i < 6; i++) {
2187 macaddr[i] = strtol(p, (char **)&p, 16);
2200 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
2205 p1 = strchr(p, sep);
2211 if (len > buf_size - 1)
2213 memcpy(buf, p, len);
2220 int parse_host_port(struct sockaddr_in *saddr, const char *str)
2228 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2230 saddr->sin_family = AF_INET;
2231 if (buf[0] == '\0') {
2232 saddr->sin_addr.s_addr = 0;
2234 if (isdigit(buf[0])) {
2235 if (!inet_aton(buf, &saddr->sin_addr))
2238 if ((he = gethostbyname(buf)) == NULL)
2240 saddr->sin_addr = *(struct in_addr *)he->h_addr;
2243 port = strtol(p, (char **)&r, 0);
2246 saddr->sin_port = htons(port);
2250 /* find or alloc a new VLAN */
2251 VLANState *qemu_find_vlan(int id)
2253 VLANState **pvlan, *vlan;
2254 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
2258 vlan = qemu_mallocz(sizeof(VLANState));
2263 pvlan = &first_vlan;
2264 while (*pvlan != NULL)
2265 pvlan = &(*pvlan)->next;
2270 VLANClientState *qemu_new_vlan_client(VLANState *vlan,
2271 IOReadHandler *fd_read,
2272 IOCanRWHandler *fd_can_read,
2275 VLANClientState *vc, **pvc;
2276 vc = qemu_mallocz(sizeof(VLANClientState));
2279 vc->fd_read = fd_read;
2280 vc->fd_can_read = fd_can_read;
2281 vc->opaque = opaque;
2285 pvc = &vlan->first_client;
2286 while (*pvc != NULL)
2287 pvc = &(*pvc)->next;
2292 int qemu_can_send_packet(VLANClientState *vc1)
2294 VLANState *vlan = vc1->vlan;
2295 VLANClientState *vc;
2297 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
2299 if (vc->fd_can_read && !vc->fd_can_read(vc->opaque))
2306 void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
2308 VLANState *vlan = vc1->vlan;
2309 VLANClientState *vc;
2312 printf("vlan %d send:\n", vlan->id);
2313 hex_dump(stdout, buf, size);
2315 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
2317 vc->fd_read(vc->opaque, buf, size);
2322 #if defined(CONFIG_SLIRP)
2324 /* slirp network adapter */
2326 static int slirp_inited;
2327 static VLANClientState *slirp_vc;
2329 int slirp_can_output(void)
2331 return !slirp_vc || qemu_can_send_packet(slirp_vc);
2334 void slirp_output(const uint8_t *pkt, int pkt_len)
2337 printf("slirp output:\n");
2338 hex_dump(stdout, pkt, pkt_len);
2342 qemu_send_packet(slirp_vc, pkt, pkt_len);
2345 static void slirp_receive(void *opaque, const uint8_t *buf, int size)
2348 printf("slirp input:\n");
2349 hex_dump(stdout, buf, size);
2351 slirp_input(buf, size);
2354 static int net_slirp_init(VLANState *vlan)
2356 if (!slirp_inited) {
2360 slirp_vc = qemu_new_vlan_client(vlan,
2361 slirp_receive, NULL, NULL);
2362 snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
2366 static void net_slirp_redir(const char *redir_str)
2371 struct in_addr guest_addr;
2372 int host_port, guest_port;
2374 if (!slirp_inited) {
2380 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2382 if (!strcmp(buf, "tcp")) {
2384 } else if (!strcmp(buf, "udp")) {
2390 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2392 host_port = strtol(buf, &r, 0);
2396 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2398 if (buf[0] == '\0') {
2399 pstrcpy(buf, sizeof(buf), "10.0.2.15");
2401 if (!inet_aton(buf, &guest_addr))
2404 guest_port = strtol(p, &r, 0);
2408 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
2409 fprintf(stderr, "qemu: could not set up redirection\n");
2414 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
2422 static void smb_exit(void)
2426 char filename[1024];
2428 /* erase all the files in the directory */
2429 d = opendir(smb_dir);
2434 if (strcmp(de->d_name, ".") != 0 &&
2435 strcmp(de->d_name, "..") != 0) {
2436 snprintf(filename, sizeof(filename), "%s/%s",
2437 smb_dir, de->d_name);
2445 /* automatic user mode samba server configuration */
2446 void net_slirp_smb(const char *exported_dir)
2448 char smb_conf[1024];
2449 char smb_cmdline[1024];
2452 if (!slirp_inited) {
2457 /* XXX: better tmp dir construction */
2458 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
2459 if (mkdir(smb_dir, 0700) < 0) {
2460 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
2463 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
2465 f = fopen(smb_conf, "w");
2467 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
2474 "socket address=127.0.0.1\n"
2475 "pid directory=%s\n"
2476 "lock directory=%s\n"
2477 "log file=%s/log.smbd\n"
2478 "smb passwd file=%s/smbpasswd\n"
2479 "security = share\n"
2494 snprintf(smb_cmdline, sizeof(smb_cmdline), "/usr/sbin/smbd -s %s",
2497 slirp_add_exec(0, smb_cmdline, 4, 139);
2500 #endif /* !defined(_WIN32) */
2502 #endif /* CONFIG_SLIRP */
2504 #if !defined(_WIN32)
2506 typedef struct TAPState {
2507 VLANClientState *vc;
2511 static void tap_receive(void *opaque, const uint8_t *buf, int size)
2513 TAPState *s = opaque;
2516 ret = write(s->fd, buf, size);
2517 if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
2524 static void tap_send(void *opaque)
2526 TAPState *s = opaque;
2530 size = read(s->fd, buf, sizeof(buf));
2532 qemu_send_packet(s->vc, buf, size);
2538 static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
2542 s = qemu_mallocz(sizeof(TAPState));
2546 s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
2547 qemu_set_fd_handler(s->fd, tap_send, NULL, s);
2548 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
2553 static int tap_open(char *ifname, int ifname_size)
2559 fd = open("/dev/tap", O_RDWR);
2561 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
2566 dev = devname(s.st_rdev, S_IFCHR);
2567 pstrcpy(ifname, ifname_size, dev);
2569 fcntl(fd, F_SETFL, O_NONBLOCK);
2572 #elif defined(__sun__)
2573 static int tap_open(char *ifname, int ifname_size)
2575 fprintf(stderr, "warning: tap_open not yet implemented\n");
2579 static int tap_open(char *ifname, int ifname_size)
2584 fd = open("/dev/net/tun", O_RDWR);
2586 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
2589 memset(&ifr, 0, sizeof(ifr));
2590 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
2591 if (ifname[0] != '\0')
2592 pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
2594 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
2595 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
2597 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
2601 pstrcpy(ifname, ifname_size, ifr.ifr_name);
2602 fcntl(fd, F_SETFL, O_NONBLOCK);
2607 static int net_tap_init(VLANState *vlan, const char *ifname1,
2608 const char *setup_script)
2611 int pid, status, fd;
2616 if (ifname1 != NULL)
2617 pstrcpy(ifname, sizeof(ifname), ifname1);
2620 fd = tap_open(ifname, sizeof(ifname));
2626 if (setup_script[0] != '\0') {
2627 /* try to launch network init script */
2632 *parg++ = (char *)setup_script;
2635 execv(setup_script, args);
2638 while (waitpid(pid, &status, 0) != pid);
2639 if (!WIFEXITED(status) ||
2640 WEXITSTATUS(status) != 0) {
2641 fprintf(stderr, "%s: could not launch network script\n",
2647 s = net_tap_fd_init(vlan, fd);
2650 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
2651 "tap: ifname=%s setup_script=%s", ifname, setup_script);
2655 #endif /* !_WIN32 */
2657 /* network connection */
2658 typedef struct NetSocketState {
2659 VLANClientState *vc;
2661 int state; /* 0 = getting length, 1 = getting data */
2665 struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
2668 typedef struct NetSocketListenState {
2671 } NetSocketListenState;
2673 /* XXX: we consider we can send the whole packet without blocking */
2674 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
2676 NetSocketState *s = opaque;
2680 send_all(s->fd, (const uint8_t *)&len, sizeof(len));
2681 send_all(s->fd, buf, size);
2684 static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
2686 NetSocketState *s = opaque;
2687 sendto(s->fd, buf, size, 0,
2688 (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
2691 static void net_socket_send(void *opaque)
2693 NetSocketState *s = opaque;
2698 size = recv(s->fd, buf1, sizeof(buf1), 0);
2700 err = socket_error();
2701 if (err != EWOULDBLOCK)
2703 } else if (size == 0) {
2704 /* end of connection */
2706 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2712 /* reassemble a packet from the network */
2718 memcpy(s->buf + s->index, buf, l);
2722 if (s->index == 4) {
2724 s->packet_len = ntohl(*(uint32_t *)s->buf);
2730 l = s->packet_len - s->index;
2733 memcpy(s->buf + s->index, buf, l);
2737 if (s->index >= s->packet_len) {
2738 qemu_send_packet(s->vc, s->buf, s->packet_len);
2747 static void net_socket_send_dgram(void *opaque)
2749 NetSocketState *s = opaque;
2752 size = recv(s->fd, s->buf, sizeof(s->buf), 0);
2756 /* end of connection */
2757 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2760 qemu_send_packet(s->vc, s->buf, size);
2763 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
2768 if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
2769 fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
2770 inet_ntoa(mcastaddr->sin_addr),
2771 (int)ntohl(mcastaddr->sin_addr.s_addr));
2775 fd = socket(PF_INET, SOCK_DGRAM, 0);
2777 perror("socket(PF_INET, SOCK_DGRAM)");
2782 ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
2783 (const char *)&val, sizeof(val));
2785 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
2789 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
2795 /* Add host to multicast group */
2796 imr.imr_multiaddr = mcastaddr->sin_addr;
2797 imr.imr_interface.s_addr = htonl(INADDR_ANY);
2799 ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
2800 (const char *)&imr, sizeof(struct ip_mreq));
2802 perror("setsockopt(IP_ADD_MEMBERSHIP)");
2806 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
2808 ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
2809 (const char *)&val, sizeof(val));
2811 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
2815 socket_set_nonblock(fd);
2818 if (fd>=0) close(fd);
2822 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd,
2825 struct sockaddr_in saddr;
2827 socklen_t saddr_len;
2830 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
2831 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
2832 * by ONLY ONE process: we must "clone" this dgram socket --jjo
2836 if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
2838 if (saddr.sin_addr.s_addr==0) {
2839 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
2843 /* clone dgram socket */
2844 newfd = net_socket_mcast_create(&saddr);
2846 /* error already reported by net_socket_mcast_create() */
2850 /* clone newfd to fd, close newfd */
2855 fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
2856 fd, strerror(errno));
2861 s = qemu_mallocz(sizeof(NetSocketState));
2866 s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
2867 qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
2869 /* mcast: save bound address as dst */
2870 if (is_connected) s->dgram_dst=saddr;
2872 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
2873 "socket: fd=%d (%s mcast=%s:%d)",
2874 fd, is_connected? "cloned" : "",
2875 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
2879 static void net_socket_connect(void *opaque)
2881 NetSocketState *s = opaque;
2882 qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
2885 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd,
2889 s = qemu_mallocz(sizeof(NetSocketState));
2893 s->vc = qemu_new_vlan_client(vlan,
2894 net_socket_receive, NULL, s);
2895 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
2896 "socket: fd=%d", fd);
2898 net_socket_connect(s);
2900 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
2905 static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
2908 int so_type=-1, optlen=sizeof(so_type);
2910 if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type, &optlen)< 0) {
2911 fprintf(stderr, "qemu: error: setsockopt(SO_TYPE) for fd=%d failed\n", fd);
2916 return net_socket_fd_init_dgram(vlan, fd, is_connected);
2918 return net_socket_fd_init_stream(vlan, fd, is_connected);
2920 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
2921 fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
2922 return net_socket_fd_init_stream(vlan, fd, is_connected);
2927 static void net_socket_accept(void *opaque)
2929 NetSocketListenState *s = opaque;
2931 struct sockaddr_in saddr;
2936 len = sizeof(saddr);
2937 fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
2938 if (fd < 0 && errno != EINTR) {
2940 } else if (fd >= 0) {
2944 s1 = net_socket_fd_init(s->vlan, fd, 1);
2948 snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
2949 "socket: connection from %s:%d",
2950 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
2954 static int net_socket_listen_init(VLANState *vlan, const char *host_str)
2956 NetSocketListenState *s;
2958 struct sockaddr_in saddr;
2960 if (parse_host_port(&saddr, host_str) < 0)
2963 s = qemu_mallocz(sizeof(NetSocketListenState));
2967 fd = socket(PF_INET, SOCK_STREAM, 0);
2972 socket_set_nonblock(fd);
2974 /* allow fast reuse */
2976 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
2978 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
2983 ret = listen(fd, 0);
2990 qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
2994 static int net_socket_connect_init(VLANState *vlan, const char *host_str)
2997 int fd, connected, ret, err;
2998 struct sockaddr_in saddr;
3000 if (parse_host_port(&saddr, host_str) < 0)
3003 fd = socket(PF_INET, SOCK_STREAM, 0);
3008 socket_set_nonblock(fd);
3012 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
3014 err = socket_error();
3015 if (err == EINTR || err == EWOULDBLOCK) {
3016 } else if (err == EINPROGRESS) {
3028 s = net_socket_fd_init(vlan, fd, connected);
3031 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3032 "socket: connect to %s:%d",
3033 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3037 static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
3041 struct sockaddr_in saddr;
3043 if (parse_host_port(&saddr, host_str) < 0)
3047 fd = net_socket_mcast_create(&saddr);
3051 s = net_socket_fd_init(vlan, fd, 0);
3055 s->dgram_dst = saddr;
3057 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3058 "socket: mcast=%s:%d",
3059 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3064 static int get_param_value(char *buf, int buf_size,
3065 const char *tag, const char *str)
3074 while (*p != '\0' && *p != '=') {
3075 if ((q - option) < sizeof(option) - 1)
3083 if (!strcmp(tag, option)) {
3085 while (*p != '\0' && *p != ',') {
3086 if ((q - buf) < buf_size - 1)
3093 while (*p != '\0' && *p != ',') {
3104 int net_client_init(const char *str)
3115 while (*p != '\0' && *p != ',') {
3116 if ((q - device) < sizeof(device) - 1)
3124 if (get_param_value(buf, sizeof(buf), "vlan", p)) {
3125 vlan_id = strtol(buf, NULL, 0);
3127 vlan = qemu_find_vlan(vlan_id);
3129 fprintf(stderr, "Could not create vlan %d\n", vlan_id);
3132 if (!strcmp(device, "nic")) {
3136 if (nb_nics >= MAX_NICS) {
3137 fprintf(stderr, "Too Many NICs\n");
3140 nd = &nd_table[nb_nics];
3141 macaddr = nd->macaddr;
3147 macaddr[5] = 0x56 + nb_nics;
3149 if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
3150 if (parse_macaddr(macaddr, buf) < 0) {
3151 fprintf(stderr, "invalid syntax for ethernet address\n");
3155 if (get_param_value(buf, sizeof(buf), "model", p)) {
3156 nd->model = strdup(buf);
3162 if (!strcmp(device, "none")) {
3163 /* does nothing. It is needed to signal that no network cards
3168 if (!strcmp(device, "user")) {
3169 if (get_param_value(buf, sizeof(buf), "hostname", p)) {
3170 pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
3172 ret = net_slirp_init(vlan);
3176 if (!strcmp(device, "tap")) {
3178 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
3179 fprintf(stderr, "tap: no interface name\n");
3182 ret = tap_win32_init(vlan, ifname);
3185 if (!strcmp(device, "tap")) {
3187 char setup_script[1024];
3189 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
3190 fd = strtol(buf, NULL, 0);
3192 if (net_tap_fd_init(vlan, fd))
3195 get_param_value(ifname, sizeof(ifname), "ifname", p);
3196 if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
3197 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
3199 ret = net_tap_init(vlan, ifname, setup_script);
3203 if (!strcmp(device, "socket")) {
3204 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
3206 fd = strtol(buf, NULL, 0);
3208 if (net_socket_fd_init(vlan, fd, 1))
3210 } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
3211 ret = net_socket_listen_init(vlan, buf);
3212 } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
3213 ret = net_socket_connect_init(vlan, buf);
3214 } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
3215 ret = net_socket_mcast_init(vlan, buf);
3217 fprintf(stderr, "Unknown socket options: %s\n", p);
3222 fprintf(stderr, "Unknown network device: %s\n", device);
3226 fprintf(stderr, "Could not initialize device '%s'\n", device);
3232 void do_info_network(void)
3235 VLANClientState *vc;
3237 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
3238 term_printf("VLAN %d devices:\n", vlan->id);
3239 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
3240 term_printf(" %s\n", vc->info_str);
3244 /***********************************************************/
3247 static int usb_device_add(const char *devname)
3255 for(i = 0;i < MAX_VM_USB_PORTS; i++) {
3256 if (!vm_usb_ports[i]->dev)
3259 if (i == MAX_VM_USB_PORTS)
3262 if (strstart(devname, "host:", &p)) {
3263 dev = usb_host_device_open(p);
3266 } else if (!strcmp(devname, "mouse")) {
3267 dev = usb_mouse_init();
3270 } else if (!strcmp(devname, "tablet")) {
3271 dev = usb_tablet_init();
3277 usb_attach(vm_usb_ports[i], dev);
3281 static int usb_device_del(const char *devname)
3284 int bus_num, addr, i;
3290 p = strchr(devname, '.');
3293 bus_num = strtoul(devname, NULL, 0);
3294 addr = strtoul(p + 1, NULL, 0);
3297 for(i = 0;i < MAX_VM_USB_PORTS; i++) {
3298 dev = vm_usb_ports[i]->dev;
3299 if (dev && dev->addr == addr)
3302 if (i == MAX_VM_USB_PORTS)
3304 usb_attach(vm_usb_ports[i], NULL);
3308 void do_usb_add(const char *devname)
3311 ret = usb_device_add(devname);
3313 term_printf("Could not add USB device '%s'\n", devname);
3316 void do_usb_del(const char *devname)
3319 ret = usb_device_del(devname);
3321 term_printf("Could not remove USB device '%s'\n", devname);
3328 const char *speed_str;
3331 term_printf("USB support not enabled\n");
3335 for(i = 0; i < MAX_VM_USB_PORTS; i++) {
3336 dev = vm_usb_ports[i]->dev;
3338 term_printf("Hub port %d:\n", i);
3339 switch(dev->speed) {
3343 case USB_SPEED_FULL:
3346 case USB_SPEED_HIGH:
3353 term_printf(" Device %d.%d, speed %s Mb/s\n",
3354 0, dev->addr, speed_str);
3359 /***********************************************************/
3362 static char *pid_filename;
3364 /* Remove PID file. Called on normal exit */
3366 static void remove_pidfile(void)
3368 unlink (pid_filename);
3371 static void create_pidfile(const char *filename)
3373 struct stat pidstat;
3376 /* Try to write our PID to the named file */
3377 if (stat(filename, &pidstat) < 0) {
3378 if (errno == ENOENT) {
3379 if ((f = fopen (filename, "w")) == NULL) {
3380 perror("Opening pidfile");
3383 fprintf(f, "%d\n", getpid());
3385 pid_filename = qemu_strdup(filename);
3386 if (!pid_filename) {
3387 fprintf(stderr, "Could not save PID filename");
3390 atexit(remove_pidfile);
3393 fprintf(stderr, "%s already exists. Remove it and try again.\n",
3399 /***********************************************************/
3402 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
3406 static void dumb_resize(DisplayState *ds, int w, int h)
3410 static void dumb_refresh(DisplayState *ds)
3415 void dumb_display_init(DisplayState *ds)
3420 ds->dpy_update = dumb_update;
3421 ds->dpy_resize = dumb_resize;
3422 ds->dpy_refresh = dumb_refresh;
3425 #if !defined(CONFIG_SOFTMMU)
3426 /***********************************************************/
3427 /* cpu signal handler */
3428 static void host_segv_handler(int host_signum, siginfo_t *info,
3431 if (cpu_signal_handler(host_signum, info, puc))
3433 if (stdio_nb_clients > 0)
3439 /***********************************************************/
3442 #define MAX_IO_HANDLERS 64
3444 typedef struct IOHandlerRecord {
3446 IOCanRWHandler *fd_read_poll;
3448 IOHandler *fd_write;
3450 /* temporary data */
3452 struct IOHandlerRecord *next;
3455 static IOHandlerRecord *first_io_handler;
3457 /* XXX: fd_read_poll should be suppressed, but an API change is
3458 necessary in the character devices to suppress fd_can_read(). */
3459 int qemu_set_fd_handler2(int fd,
3460 IOCanRWHandler *fd_read_poll,
3462 IOHandler *fd_write,
3465 IOHandlerRecord **pioh, *ioh;
3467 if (!fd_read && !fd_write) {
3468 pioh = &first_io_handler;
3473 if (ioh->fd == fd) {
3481 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3485 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
3488 ioh->next = first_io_handler;
3489 first_io_handler = ioh;
3492 ioh->fd_read_poll = fd_read_poll;
3493 ioh->fd_read = fd_read;
3494 ioh->fd_write = fd_write;
3495 ioh->opaque = opaque;
3500 int qemu_set_fd_handler(int fd,
3502 IOHandler *fd_write,
3505 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
3508 /***********************************************************/
3509 /* Polling handling */
3511 typedef struct PollingEntry {
3514 struct PollingEntry *next;
3517 static PollingEntry *first_polling_entry;
3519 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
3521 PollingEntry **ppe, *pe;
3522 pe = qemu_mallocz(sizeof(PollingEntry));
3526 pe->opaque = opaque;
3527 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
3532 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
3534 PollingEntry **ppe, *pe;
3535 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
3537 if (pe->func == func && pe->opaque == opaque) {
3545 /***********************************************************/
3546 /* savevm/loadvm support */
3548 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
3550 fwrite(buf, 1, size, f);
3553 void qemu_put_byte(QEMUFile *f, int v)
3558 void qemu_put_be16(QEMUFile *f, unsigned int v)
3560 qemu_put_byte(f, v >> 8);
3561 qemu_put_byte(f, v);
3564 void qemu_put_be32(QEMUFile *f, unsigned int v)
3566 qemu_put_byte(f, v >> 24);
3567 qemu_put_byte(f, v >> 16);
3568 qemu_put_byte(f, v >> 8);
3569 qemu_put_byte(f, v);
3572 void qemu_put_be64(QEMUFile *f, uint64_t v)
3574 qemu_put_be32(f, v >> 32);
3575 qemu_put_be32(f, v);
3578 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size)
3580 return fread(buf, 1, size, f);
3583 int qemu_get_byte(QEMUFile *f)
3593 unsigned int qemu_get_be16(QEMUFile *f)
3596 v = qemu_get_byte(f) << 8;
3597 v |= qemu_get_byte(f);
3601 unsigned int qemu_get_be32(QEMUFile *f)
3604 v = qemu_get_byte(f) << 24;
3605 v |= qemu_get_byte(f) << 16;
3606 v |= qemu_get_byte(f) << 8;
3607 v |= qemu_get_byte(f);
3611 uint64_t qemu_get_be64(QEMUFile *f)
3614 v = (uint64_t)qemu_get_be32(f) << 32;
3615 v |= qemu_get_be32(f);
3619 int64_t qemu_ftell(QEMUFile *f)
3624 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
3626 if (fseek(f, pos, whence) < 0)
3631 typedef struct SaveStateEntry {
3635 SaveStateHandler *save_state;
3636 LoadStateHandler *load_state;
3638 struct SaveStateEntry *next;
3641 static SaveStateEntry *first_se;
3643 int register_savevm(const char *idstr,
3646 SaveStateHandler *save_state,
3647 LoadStateHandler *load_state,
3650 SaveStateEntry *se, **pse;
3652 se = qemu_malloc(sizeof(SaveStateEntry));
3655 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
3656 se->instance_id = instance_id;
3657 se->version_id = version_id;
3658 se->save_state = save_state;
3659 se->load_state = load_state;
3660 se->opaque = opaque;
3663 /* add at the end of list */
3665 while (*pse != NULL)
3666 pse = &(*pse)->next;
3671 #define QEMU_VM_FILE_MAGIC 0x5145564d
3672 #define QEMU_VM_FILE_VERSION 0x00000001
3674 int qemu_savevm(const char *filename)
3678 int len, len_pos, cur_pos, saved_vm_running, ret;
3680 saved_vm_running = vm_running;
3683 f = fopen(filename, "wb");
3689 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
3690 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
3692 for(se = first_se; se != NULL; se = se->next) {
3694 len = strlen(se->idstr);
3695 qemu_put_byte(f, len);
3696 qemu_put_buffer(f, se->idstr, len);
3698 qemu_put_be32(f, se->instance_id);
3699 qemu_put_be32(f, se->version_id);
3701 /* record size: filled later */
3703 qemu_put_be32(f, 0);
3705 se->save_state(f, se->opaque);
3707 /* fill record size */
3709 len = ftell(f) - len_pos - 4;
3710 fseek(f, len_pos, SEEK_SET);
3711 qemu_put_be32(f, len);
3712 fseek(f, cur_pos, SEEK_SET);
3718 if (saved_vm_running)
3723 static SaveStateEntry *find_se(const char *idstr, int instance_id)
3727 for(se = first_se; se != NULL; se = se->next) {
3728 if (!strcmp(se->idstr, idstr) &&
3729 instance_id == se->instance_id)
3735 int qemu_loadvm(const char *filename)
3739 int len, cur_pos, ret, instance_id, record_len, version_id;
3740 int saved_vm_running;
3744 saved_vm_running = vm_running;
3747 f = fopen(filename, "rb");
3753 v = qemu_get_be32(f);
3754 if (v != QEMU_VM_FILE_MAGIC)
3756 v = qemu_get_be32(f);
3757 if (v != QEMU_VM_FILE_VERSION) {
3764 len = qemu_get_byte(f);
3767 qemu_get_buffer(f, idstr, len);
3769 instance_id = qemu_get_be32(f);
3770 version_id = qemu_get_be32(f);
3771 record_len = qemu_get_be32(f);
3773 printf("idstr=%s instance=0x%x version=%d len=%d\n",
3774 idstr, instance_id, version_id, record_len);
3777 se = find_se(idstr, instance_id);
3779 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
3780 instance_id, idstr);
3782 ret = se->load_state(f, se->opaque, version_id);
3784 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
3785 instance_id, idstr);
3788 /* always seek to exact end of record */
3789 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
3794 if (saved_vm_running)
3799 /***********************************************************/
3800 /* cpu save/restore */
3802 #if defined(TARGET_I386)
3804 static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
3806 qemu_put_be32(f, dt->selector);
3807 qemu_put_betl(f, dt->base);
3808 qemu_put_be32(f, dt->limit);
3809 qemu_put_be32(f, dt->flags);
3812 static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
3814 dt->selector = qemu_get_be32(f);
3815 dt->base = qemu_get_betl(f);
3816 dt->limit = qemu_get_be32(f);
3817 dt->flags = qemu_get_be32(f);
3820 void cpu_save(QEMUFile *f, void *opaque)
3822 CPUState *env = opaque;
3823 uint16_t fptag, fpus, fpuc, fpregs_format;
3827 for(i = 0; i < CPU_NB_REGS; i++)
3828 qemu_put_betls(f, &env->regs[i]);
3829 qemu_put_betls(f, &env->eip);
3830 qemu_put_betls(f, &env->eflags);
3831 hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
3832 qemu_put_be32s(f, &hflags);
3836 fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
3838 for(i = 0; i < 8; i++) {
3839 fptag |= ((!env->fptags[i]) << i);
3842 qemu_put_be16s(f, &fpuc);
3843 qemu_put_be16s(f, &fpus);
3844 qemu_put_be16s(f, &fptag);
3846 #ifdef USE_X86LDOUBLE
3851 qemu_put_be16s(f, &fpregs_format);
3853 for(i = 0; i < 8; i++) {
3854 #ifdef USE_X86LDOUBLE
3858 /* we save the real CPU data (in case of MMX usage only 'mant'
3859 contains the MMX register */
3860 cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
3861 qemu_put_be64(f, mant);
3862 qemu_put_be16(f, exp);
3865 /* if we use doubles for float emulation, we save the doubles to
3866 avoid losing information in case of MMX usage. It can give
3867 problems if the image is restored on a CPU where long
3868 doubles are used instead. */
3869 qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
3873 for(i = 0; i < 6; i++)
3874 cpu_put_seg(f, &env->segs[i]);
3875 cpu_put_seg(f, &env->ldt);
3876 cpu_put_seg(f, &env->tr);
3877 cpu_put_seg(f, &env->gdt);
3878 cpu_put_seg(f, &env->idt);
3880 qemu_put_be32s(f, &env->sysenter_cs);
3881 qemu_put_be32s(f, &env->sysenter_esp);
3882 qemu_put_be32s(f, &env->sysenter_eip);
3884 qemu_put_betls(f, &env->cr[0]);
3885 qemu_put_betls(f, &env->cr[2]);
3886 qemu_put_betls(f, &env->cr[3]);
3887 qemu_put_betls(f, &env->cr[4]);
3889 for(i = 0; i < 8; i++)
3890 qemu_put_betls(f, &env->dr[i]);
3893 qemu_put_be32s(f, &env->a20_mask);
3896 qemu_put_be32s(f, &env->mxcsr);
3897 for(i = 0; i < CPU_NB_REGS; i++) {
3898 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
3899 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
3902 #ifdef TARGET_X86_64
3903 qemu_put_be64s(f, &env->efer);
3904 qemu_put_be64s(f, &env->star);
3905 qemu_put_be64s(f, &env->lstar);
3906 qemu_put_be64s(f, &env->cstar);
3907 qemu_put_be64s(f, &env->fmask);
3908 qemu_put_be64s(f, &env->kernelgsbase);
3912 #ifdef USE_X86LDOUBLE
3913 /* XXX: add that in a FPU generic layer */
3914 union x86_longdouble {
3919 #define MANTD1(fp) (fp & ((1LL << 52) - 1))
3920 #define EXPBIAS1 1023
3921 #define EXPD1(fp) ((fp >> 52) & 0x7FF)
3922 #define SIGND1(fp) ((fp >> 32) & 0x80000000)
3924 static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
3928 p->mant = (MANTD1(temp) << 11) | (1LL << 63);
3929 /* exponent + sign */
3930 e = EXPD1(temp) - EXPBIAS1 + 16383;
3931 e |= SIGND1(temp) >> 16;
3936 int cpu_load(QEMUFile *f, void *opaque, int version_id)
3938 CPUState *env = opaque;
3941 uint16_t fpus, fpuc, fptag, fpregs_format;
3943 if (version_id != 3)
3945 for(i = 0; i < CPU_NB_REGS; i++)
3946 qemu_get_betls(f, &env->regs[i]);
3947 qemu_get_betls(f, &env->eip);
3948 qemu_get_betls(f, &env->eflags);
3949 qemu_get_be32s(f, &hflags);
3951 qemu_get_be16s(f, &fpuc);
3952 qemu_get_be16s(f, &fpus);
3953 qemu_get_be16s(f, &fptag);
3954 qemu_get_be16s(f, &fpregs_format);
3956 /* NOTE: we cannot always restore the FPU state if the image come
3957 from a host with a different 'USE_X86LDOUBLE' define. We guess
3958 if we are in an MMX state to restore correctly in that case. */
3959 guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
3960 for(i = 0; i < 8; i++) {
3964 switch(fpregs_format) {
3966 mant = qemu_get_be64(f);
3967 exp = qemu_get_be16(f);
3968 #ifdef USE_X86LDOUBLE
3969 env->fpregs[i].d = cpu_set_fp80(mant, exp);
3971 /* difficult case */
3973 env->fpregs[i].mmx.MMX_Q(0) = mant;
3975 env->fpregs[i].d = cpu_set_fp80(mant, exp);
3979 mant = qemu_get_be64(f);
3980 #ifdef USE_X86LDOUBLE
3982 union x86_longdouble *p;
3983 /* difficult case */
3984 p = (void *)&env->fpregs[i];
3989 fp64_to_fp80(p, mant);
3993 env->fpregs[i].mmx.MMX_Q(0) = mant;
4002 /* XXX: restore FPU round state */
4003 env->fpstt = (fpus >> 11) & 7;
4004 env->fpus = fpus & ~0x3800;
4006 for(i = 0; i < 8; i++) {
4007 env->fptags[i] = (fptag >> i) & 1;
4010 for(i = 0; i < 6; i++)
4011 cpu_get_seg(f, &env->segs[i]);
4012 cpu_get_seg(f, &env->ldt);
4013 cpu_get_seg(f, &env->tr);
4014 cpu_get_seg(f, &env->gdt);
4015 cpu_get_seg(f, &env->idt);
4017 qemu_get_be32s(f, &env->sysenter_cs);
4018 qemu_get_be32s(f, &env->sysenter_esp);
4019 qemu_get_be32s(f, &env->sysenter_eip);
4021 qemu_get_betls(f, &env->cr[0]);
4022 qemu_get_betls(f, &env->cr[2]);
4023 qemu_get_betls(f, &env->cr[3]);
4024 qemu_get_betls(f, &env->cr[4]);
4026 for(i = 0; i < 8; i++)
4027 qemu_get_betls(f, &env->dr[i]);
4030 qemu_get_be32s(f, &env->a20_mask);
4032 qemu_get_be32s(f, &env->mxcsr);
4033 for(i = 0; i < CPU_NB_REGS; i++) {
4034 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
4035 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
4038 #ifdef TARGET_X86_64
4039 qemu_get_be64s(f, &env->efer);
4040 qemu_get_be64s(f, &env->star);
4041 qemu_get_be64s(f, &env->lstar);
4042 qemu_get_be64s(f, &env->cstar);
4043 qemu_get_be64s(f, &env->fmask);
4044 qemu_get_be64s(f, &env->kernelgsbase);
4047 /* XXX: compute hflags from scratch, except for CPL and IIF */
4048 env->hflags = hflags;
4053 #elif defined(TARGET_PPC)
4054 void cpu_save(QEMUFile *f, void *opaque)
4058 int cpu_load(QEMUFile *f, void *opaque, int version_id)
4063 #elif defined(TARGET_MIPS)
4064 void cpu_save(QEMUFile *f, void *opaque)
4068 int cpu_load(QEMUFile *f, void *opaque, int version_id)
4073 #elif defined(TARGET_SPARC)
4074 void cpu_save(QEMUFile *f, void *opaque)
4076 CPUState *env = opaque;
4080 for(i = 0; i < 8; i++)
4081 qemu_put_betls(f, &env->gregs[i]);
4082 for(i = 0; i < NWINDOWS * 16; i++)
4083 qemu_put_betls(f, &env->regbase[i]);
4086 for(i = 0; i < TARGET_FPREGS; i++) {
4092 qemu_put_betl(f, u.i);
4095 qemu_put_betls(f, &env->pc);
4096 qemu_put_betls(f, &env->npc);
4097 qemu_put_betls(f, &env->y);
4099 qemu_put_be32(f, tmp);
4100 qemu_put_betls(f, &env->fsr);
4101 qemu_put_betls(f, &env->tbr);
4102 #ifndef TARGET_SPARC64
4103 qemu_put_be32s(f, &env->wim);
4105 for(i = 0; i < 16; i++)
4106 qemu_put_be32s(f, &env->mmuregs[i]);
4110 int cpu_load(QEMUFile *f, void *opaque, int version_id)
4112 CPUState *env = opaque;
4116 for(i = 0; i < 8; i++)
4117 qemu_get_betls(f, &env->gregs[i]);
4118 for(i = 0; i < NWINDOWS * 16; i++)
4119 qemu_get_betls(f, &env->regbase[i]);
4122 for(i = 0; i < TARGET_FPREGS; i++) {
4127 u.i = qemu_get_betl(f);
4131 qemu_get_betls(f, &env->pc);
4132 qemu_get_betls(f, &env->npc);
4133 qemu_get_betls(f, &env->y);
4134 tmp = qemu_get_be32(f);
4135 env->cwp = 0; /* needed to ensure that the wrapping registers are
4136 correctly updated */
4138 qemu_get_betls(f, &env->fsr);
4139 qemu_get_betls(f, &env->tbr);
4140 #ifndef TARGET_SPARC64
4141 qemu_get_be32s(f, &env->wim);
4143 for(i = 0; i < 16; i++)
4144 qemu_get_be32s(f, &env->mmuregs[i]);
4150 #elif defined(TARGET_ARM)
4152 /* ??? Need to implement these. */
4153 void cpu_save(QEMUFile *f, void *opaque)
4157 int cpu_load(QEMUFile *f, void *opaque, int version_id)
4164 #warning No CPU save/restore functions
4168 /***********************************************************/
4169 /* ram save/restore */
4171 /* we just avoid storing empty pages */
4172 static void ram_put_page(QEMUFile *f, const uint8_t *buf, int len)
4177 for(i = 1; i < len; i++) {
4181 qemu_put_byte(f, 1);
4182 qemu_put_byte(f, v);
4185 qemu_put_byte(f, 0);
4186 qemu_put_buffer(f, buf, len);
4189 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
4193 v = qemu_get_byte(f);
4196 if (qemu_get_buffer(f, buf, len) != len)
4200 v = qemu_get_byte(f);
4201 memset(buf, v, len);
4209 static void ram_save(QEMUFile *f, void *opaque)
4212 qemu_put_be32(f, phys_ram_size);
4213 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
4214 ram_put_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
4218 static int ram_load(QEMUFile *f, void *opaque, int version_id)
4222 if (version_id != 1)
4224 if (qemu_get_be32(f) != phys_ram_size)
4226 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
4227 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
4234 /***********************************************************/
4235 /* machine registration */
4237 QEMUMachine *first_machine = NULL;
4239 int qemu_register_machine(QEMUMachine *m)
4242 pm = &first_machine;
4250 QEMUMachine *find_machine(const char *name)
4254 for(m = first_machine; m != NULL; m = m->next) {
4255 if (!strcmp(m->name, name))
4261 /***********************************************************/
4262 /* main execution loop */
4264 void gui_update(void *opaque)
4266 display_state.dpy_refresh(&display_state);
4267 qemu_mod_timer(gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
4270 struct vm_change_state_entry {
4271 VMChangeStateHandler *cb;
4273 LIST_ENTRY (vm_change_state_entry) entries;
4276 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
4278 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
4281 VMChangeStateEntry *e;
4283 e = qemu_mallocz(sizeof (*e));
4289 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
4293 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
4295 LIST_REMOVE (e, entries);
4299 static void vm_state_notify(int running)
4301 VMChangeStateEntry *e;
4303 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
4304 e->cb(e->opaque, running);
4308 /* XXX: support several handlers */
4309 static VMStopHandler *vm_stop_cb;
4310 static void *vm_stop_opaque;
4312 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
4315 vm_stop_opaque = opaque;
4319 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
4333 void vm_stop(int reason)
4336 cpu_disable_ticks();
4340 vm_stop_cb(vm_stop_opaque, reason);
4347 /* reset/shutdown handler */
4349 typedef struct QEMUResetEntry {
4350 QEMUResetHandler *func;
4352 struct QEMUResetEntry *next;
4355 static QEMUResetEntry *first_reset_entry;
4356 static int reset_requested;
4357 static int shutdown_requested;
4358 static int powerdown_requested;
4360 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
4362 QEMUResetEntry **pre, *re;
4364 pre = &first_reset_entry;
4365 while (*pre != NULL)
4366 pre = &(*pre)->next;
4367 re = qemu_mallocz(sizeof(QEMUResetEntry));
4369 re->opaque = opaque;
4374 void qemu_system_reset(void)
4378 /* reset all devices */
4379 for(re = first_reset_entry; re != NULL; re = re->next) {
4380 re->func(re->opaque);
4384 void qemu_system_reset_request(void)
4386 reset_requested = 1;
4388 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
4391 void qemu_system_shutdown_request(void)
4393 shutdown_requested = 1;
4395 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
4398 void qemu_system_powerdown_request(void)
4400 powerdown_requested = 1;
4402 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
4405 void main_loop_wait(int timeout)
4407 IOHandlerRecord *ioh, *ioh_next;
4414 /* XXX: need to suppress polling by better using win32 events */
4416 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
4417 ret |= pe->func(pe->opaque);
4420 if (ret == 0 && timeout > 0) {
4424 hEvents[0] = host_alarm;
4425 ret = WaitForMultipleObjects(1, hEvents, FALSE, timeout);
4427 case WAIT_OBJECT_0 + 0:
4432 err = GetLastError();
4433 fprintf(stderr, "Wait error %d %d\n", ret, err);
4438 /* poll any events */
4439 /* XXX: separate device handlers from system ones */
4443 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4445 (!ioh->fd_read_poll ||
4446 ioh->fd_read_poll(ioh->opaque) != 0)) {
4447 FD_SET(ioh->fd, &rfds);
4451 if (ioh->fd_write) {
4452 FD_SET(ioh->fd, &wfds);
4462 tv.tv_usec = timeout * 1000;
4464 ret = select(nfds + 1, &rfds, &wfds, NULL, &tv);
4466 /* XXX: better handling of removal */
4467 for(ioh = first_io_handler; ioh != NULL; ioh = ioh_next) {
4468 ioh_next = ioh->next;
4469 if (FD_ISSET(ioh->fd, &rfds)) {
4470 ioh->fd_read(ioh->opaque);
4472 if (FD_ISSET(ioh->fd, &wfds)) {
4473 ioh->fd_write(ioh->opaque);
4481 #if defined(CONFIG_SLIRP)
4482 /* XXX: merge with the previous select() */
4484 fd_set rfds, wfds, xfds;
4492 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
4495 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
4497 slirp_select_poll(&rfds, &wfds, &xfds);
4503 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
4504 qemu_get_clock(vm_clock));
4505 /* run dma transfers, if any */
4509 /* real time timers */
4510 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
4511 qemu_get_clock(rt_clock));
4514 static CPUState *cur_cpu;
4519 #ifdef CONFIG_PROFILER
4524 cur_cpu = first_cpu;
4531 env = env->next_cpu;
4534 #ifdef CONFIG_PROFILER
4535 ti = profile_getclock();
4537 ret = cpu_exec(env);
4538 #ifdef CONFIG_PROFILER
4539 qemu_time += profile_getclock() - ti;
4541 if (ret != EXCP_HALTED)
4543 /* all CPUs are halted ? */
4544 if (env == cur_cpu) {
4551 if (shutdown_requested) {
4552 ret = EXCP_INTERRUPT;
4555 if (reset_requested) {
4556 reset_requested = 0;
4557 qemu_system_reset();
4558 ret = EXCP_INTERRUPT;
4560 if (powerdown_requested) {
4561 powerdown_requested = 0;
4562 qemu_system_powerdown();
4563 ret = EXCP_INTERRUPT;
4565 if (ret == EXCP_DEBUG) {
4566 vm_stop(EXCP_DEBUG);
4568 /* if hlt instruction, we wait until the next IRQ */
4569 /* XXX: use timeout computed from timers */
4570 if (ret == EXCP_HLT)
4577 #ifdef CONFIG_PROFILER
4578 ti = profile_getclock();
4580 main_loop_wait(timeout);
4581 #ifdef CONFIG_PROFILER
4582 dev_time += profile_getclock() - ti;
4585 cpu_disable_ticks();
4591 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2005 Fabrice Bellard\n"
4592 "usage: %s [options] [disk_image]\n"
4594 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4596 "Standard options:\n"
4597 "-M machine select emulated machine (-M ? for list)\n"
4598 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
4599 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
4600 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
4601 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
4602 "-boot [a|c|d] boot on floppy (a), hard disk (c) or CD-ROM (d)\n"
4603 "-snapshot write to temporary files instead of disk image files\n"
4604 "-m megs set virtual RAM size to megs MB [default=%d]\n"
4605 "-smp n set the number of CPUs to 'n' [default=1]\n"
4606 "-nographic disable graphical output and redirect serial I/Os to console\n"
4608 "-k language use keyboard layout (for example \"fr\" for French)\n"
4611 "-audio-help print list of audio drivers and their options\n"
4612 "-soundhw c1,... enable audio support\n"
4613 " and only specified sound cards (comma separated list)\n"
4614 " use -soundhw ? to get the list of supported cards\n"
4615 " use -soundhw all to enable all of them\n"
4617 "-localtime set the real time clock to local time [default=utc]\n"
4618 "-full-screen start in full screen\n"
4620 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
4622 "-usb enable the USB driver (will be the default soon)\n"
4623 "-usbdevice name add the host or guest USB device 'name'\n"
4624 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
4625 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
4628 "Network options:\n"
4629 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
4630 " create a new Network Interface Card and connect it to VLAN 'n'\n"
4632 "-net user[,vlan=n][,hostname=host]\n"
4633 " connect the user mode network stack to VLAN 'n' and send\n"
4634 " hostname 'host' to DHCP clients\n"
4637 "-net tap[,vlan=n],ifname=name\n"
4638 " connect the host TAP network interface to VLAN 'n'\n"
4640 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file]\n"
4641 " connect the host TAP network interface to VLAN 'n' and use\n"
4642 " the network script 'file' (default=%s);\n"
4643 " use 'fd=h' to connect to an already opened TAP interface\n"
4645 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
4646 " connect the vlan 'n' to another VLAN using a socket connection\n"
4647 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
4648 " connect the vlan 'n' to multicast maddr and port\n"
4649 "-net none use it alone to have zero network devices; if no -net option\n"
4650 " is provided, the default is '-net nic -net user'\n"
4653 "-tftp prefix allow tftp access to files starting with prefix [-net user]\n"
4655 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
4657 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
4658 " redirect TCP or UDP connections from host to guest [-net user]\n"
4661 "Linux boot specific:\n"
4662 "-kernel bzImage use 'bzImage' as kernel image\n"
4663 "-append cmdline use 'cmdline' as kernel command line\n"
4664 "-initrd file use 'file' as initial ram disk\n"
4666 "Debug/Expert options:\n"
4667 "-monitor dev redirect the monitor to char device 'dev'\n"
4668 "-serial dev redirect the serial port to char device 'dev'\n"
4669 "-parallel dev redirect the parallel port to char device 'dev'\n"
4670 "-pidfile file Write PID to 'file'\n"
4671 "-S freeze CPU at startup (use 'c' to start execution)\n"
4672 "-s wait gdb connection to port %d\n"
4673 "-p port change gdb connection port\n"
4674 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
4675 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
4676 " translation (t=none or lba) (usually qemu can guess them)\n"
4677 "-L path set the directory for the BIOS and VGA BIOS\n"
4679 "-no-kqemu disable KQEMU kernel module usage\n"
4681 #ifdef USE_CODE_COPY
4682 "-no-code-copy disable code copy acceleration\n"
4685 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
4686 " (default is CL-GD5446 PCI VGA)\n"
4688 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
4689 "-vnc display start a VNC server on display\n"
4691 "During emulation, the following keys are useful:\n"
4692 "ctrl-alt-f toggle full screen\n"
4693 "ctrl-alt-n switch to virtual console 'n'\n"
4694 "ctrl-alt toggle mouse and keyboard grab\n"
4696 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4698 #ifdef CONFIG_SOFTMMU
4705 DEFAULT_NETWORK_SCRIPT,
4707 DEFAULT_GDBSTUB_PORT,
4709 #ifndef CONFIG_SOFTMMU
4711 "NOTE: this version of QEMU is faster but it needs slightly patched OSes to\n"
4712 "work. Please use the 'qemu' executable to have a more accurate (but slower)\n"
4718 #define HAS_ARG 0x0001
4732 QEMU_OPTION_snapshot,
4734 QEMU_OPTION_nographic,
4736 QEMU_OPTION_audio_help,
4737 QEMU_OPTION_soundhw,
4755 QEMU_OPTION_no_code_copy,
4757 QEMU_OPTION_localtime,
4758 QEMU_OPTION_cirrusvga,
4760 QEMU_OPTION_std_vga,
4761 QEMU_OPTION_monitor,
4763 QEMU_OPTION_parallel,
4765 QEMU_OPTION_full_screen,
4766 QEMU_OPTION_pidfile,
4767 QEMU_OPTION_no_kqemu,
4768 QEMU_OPTION_kernel_kqemu,
4769 QEMU_OPTION_win2k_hack,
4771 QEMU_OPTION_usbdevice,
4776 typedef struct QEMUOption {
4782 const QEMUOption qemu_options[] = {
4783 { "h", 0, QEMU_OPTION_h },
4785 { "M", HAS_ARG, QEMU_OPTION_M },
4786 { "fda", HAS_ARG, QEMU_OPTION_fda },
4787 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
4788 { "hda", HAS_ARG, QEMU_OPTION_hda },
4789 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
4790 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
4791 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
4792 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
4793 { "boot", HAS_ARG, QEMU_OPTION_boot },
4794 { "snapshot", 0, QEMU_OPTION_snapshot },
4795 { "m", HAS_ARG, QEMU_OPTION_m },
4796 { "nographic", 0, QEMU_OPTION_nographic },
4797 { "k", HAS_ARG, QEMU_OPTION_k },
4799 { "audio-help", 0, QEMU_OPTION_audio_help },
4800 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
4803 { "net", HAS_ARG, QEMU_OPTION_net},
4805 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
4807 { "smb", HAS_ARG, QEMU_OPTION_smb },
4809 { "redir", HAS_ARG, QEMU_OPTION_redir },
4812 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
4813 { "append", HAS_ARG, QEMU_OPTION_append },
4814 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
4816 { "S", 0, QEMU_OPTION_S },
4817 { "s", 0, QEMU_OPTION_s },
4818 { "p", HAS_ARG, QEMU_OPTION_p },
4819 { "d", HAS_ARG, QEMU_OPTION_d },
4820 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
4821 { "L", HAS_ARG, QEMU_OPTION_L },
4822 { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
4824 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
4825 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
4827 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
4828 { "g", 1, QEMU_OPTION_g },
4830 { "localtime", 0, QEMU_OPTION_localtime },
4831 { "std-vga", 0, QEMU_OPTION_std_vga },
4832 { "monitor", 1, QEMU_OPTION_monitor },
4833 { "serial", 1, QEMU_OPTION_serial },
4834 { "parallel", 1, QEMU_OPTION_parallel },
4835 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
4836 { "full-screen", 0, QEMU_OPTION_full_screen },
4837 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
4838 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
4839 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
4840 { "smp", HAS_ARG, QEMU_OPTION_smp },
4841 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
4843 /* temporary options */
4844 { "usb", 0, QEMU_OPTION_usb },
4845 { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
4849 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
4851 /* this stack is only used during signal handling */
4852 #define SIGNAL_STACK_SIZE 32768
4854 static uint8_t *signal_stack;
4858 /* password input */
4860 static BlockDriverState *get_bdrv(int index)
4862 BlockDriverState *bs;
4865 bs = bs_table[index];
4866 } else if (index < 6) {
4867 bs = fd_table[index - 4];
4874 static void read_passwords(void)
4876 BlockDriverState *bs;
4880 for(i = 0; i < 6; i++) {
4882 if (bs && bdrv_is_encrypted(bs)) {
4883 term_printf("%s is encrypted.\n", bdrv_get_device_name(bs));
4884 for(j = 0; j < 3; j++) {
4885 monitor_readline("Password: ",
4886 1, password, sizeof(password));
4887 if (bdrv_set_key(bs, password) == 0)
4889 term_printf("invalid password\n");
4895 /* XXX: currently we cannot use simultaneously different CPUs */
4896 void register_machines(void)
4898 #if defined(TARGET_I386)
4899 qemu_register_machine(&pc_machine);
4900 qemu_register_machine(&isapc_machine);
4901 #elif defined(TARGET_PPC)
4902 qemu_register_machine(&heathrow_machine);
4903 qemu_register_machine(&core99_machine);
4904 qemu_register_machine(&prep_machine);
4905 #elif defined(TARGET_MIPS)
4906 qemu_register_machine(&mips_machine);
4907 #elif defined(TARGET_SPARC)
4908 #ifdef TARGET_SPARC64
4909 qemu_register_machine(&sun4u_machine);
4911 qemu_register_machine(&sun4m_machine);
4913 #elif defined(TARGET_ARM)
4914 qemu_register_machine(&integratorcp926_machine);
4915 qemu_register_machine(&integratorcp1026_machine);
4916 qemu_register_machine(&versatilepb_machine);
4917 qemu_register_machine(&versatileab_machine);
4918 #elif defined(TARGET_SH4)
4919 qemu_register_machine(&shix_machine);
4921 #error unsupported CPU
4926 struct soundhw soundhw[] = {
4933 { .init_isa = pcspk_audio_init }
4938 "Creative Sound Blaster 16",
4941 { .init_isa = SB16_init }
4948 "Yamaha YMF262 (OPL3)",
4950 "Yamaha YM3812 (OPL2)",
4954 { .init_isa = Adlib_init }
4961 "Gravis Ultrasound GF1",
4964 { .init_isa = GUS_init }
4970 "ENSONIQ AudioPCI ES1370",
4973 { .init_pci = es1370_init }
4976 { NULL, NULL, 0, 0, { NULL } }
4979 static void select_soundhw (const char *optarg)
4983 if (*optarg == '?') {
4986 printf ("Valid sound card names (comma separated):\n");
4987 for (c = soundhw; c->name; ++c) {
4988 printf ("%-11s %s\n", c->name, c->descr);
4990 printf ("\n-soundhw all will enable all of the above\n");
4991 exit (*optarg != '?');
4999 if (!strcmp (optarg, "all")) {
5000 for (c = soundhw; c->name; ++c) {
5008 e = strchr (p, ',');
5009 l = !e ? strlen (p) : (size_t) (e - p);
5011 for (c = soundhw; c->name; ++c) {
5012 if (!strncmp (c->name, p, l)) {
5021 "Unknown sound card name (too big to show)\n");
5024 fprintf (stderr, "Unknown sound card name `%.*s'\n",
5029 p += l + (e != NULL);
5033 goto show_valid_cards;
5038 #define MAX_NET_CLIENTS 32
5040 int main(int argc, char **argv)
5042 #ifdef CONFIG_GDBSTUB
5043 int use_gdbstub, gdbstub_port;
5046 int snapshot, linux_boot;
5047 const char *initrd_filename;
5048 const char *hd_filename[MAX_DISKS], *fd_filename[MAX_FD];
5049 const char *kernel_filename, *kernel_cmdline;
5050 DisplayState *ds = &display_state;
5051 int cyls, heads, secs, translation;
5052 int start_emulation = 1;
5053 char net_clients[MAX_NET_CLIENTS][256];
5056 const char *r, *optarg;
5057 CharDriverState *monitor_hd;
5058 char monitor_device[128];
5059 char serial_devices[MAX_SERIAL_PORTS][128];
5060 int serial_device_index;
5061 char parallel_devices[MAX_PARALLEL_PORTS][128];
5062 int parallel_device_index;
5063 const char *loadvm = NULL;
5064 QEMUMachine *machine;
5065 char usb_devices[MAX_VM_USB_PORTS][128];
5066 int usb_devices_index;
5068 LIST_INIT (&vm_change_state_head);
5069 #if !defined(CONFIG_SOFTMMU)
5070 /* we never want that malloc() uses mmap() */
5071 mallopt(M_MMAP_THRESHOLD, 4096 * 1024);
5073 register_machines();
5074 machine = first_machine;
5075 initrd_filename = NULL;
5076 for(i = 0; i < MAX_FD; i++)
5077 fd_filename[i] = NULL;
5078 for(i = 0; i < MAX_DISKS; i++)
5079 hd_filename[i] = NULL;
5080 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5081 vga_ram_size = VGA_RAM_SIZE;
5082 bios_size = BIOS_SIZE;
5083 #ifdef CONFIG_GDBSTUB
5085 gdbstub_port = DEFAULT_GDBSTUB_PORT;
5089 kernel_filename = NULL;
5090 kernel_cmdline = "";
5096 cyls = heads = secs = 0;
5097 translation = BIOS_ATA_TRANSLATION_AUTO;
5098 pstrcpy(monitor_device, sizeof(monitor_device), "vc");
5100 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
5101 for(i = 1; i < MAX_SERIAL_PORTS; i++)
5102 serial_devices[i][0] = '\0';
5103 serial_device_index = 0;
5105 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
5106 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
5107 parallel_devices[i][0] = '\0';
5108 parallel_device_index = 0;
5110 usb_devices_index = 0;
5115 /* default mac address of the first network interface */
5123 hd_filename[0] = argv[optind++];
5125 const QEMUOption *popt;
5128 popt = qemu_options;
5131 fprintf(stderr, "%s: invalid option -- '%s'\n",
5135 if (!strcmp(popt->name, r + 1))
5139 if (popt->flags & HAS_ARG) {
5140 if (optind >= argc) {
5141 fprintf(stderr, "%s: option '%s' requires an argument\n",
5145 optarg = argv[optind++];
5150 switch(popt->index) {
5152 machine = find_machine(optarg);
5155 printf("Supported machines are:\n");
5156 for(m = first_machine; m != NULL; m = m->next) {
5157 printf("%-10s %s%s\n",
5159 m == first_machine ? " (default)" : "");
5164 case QEMU_OPTION_initrd:
5165 initrd_filename = optarg;
5167 case QEMU_OPTION_hda:
5168 case QEMU_OPTION_hdb:
5169 case QEMU_OPTION_hdc:
5170 case QEMU_OPTION_hdd:
5173 hd_index = popt->index - QEMU_OPTION_hda;
5174 hd_filename[hd_index] = optarg;
5175 if (hd_index == cdrom_index)
5179 case QEMU_OPTION_snapshot:
5182 case QEMU_OPTION_hdachs:
5186 cyls = strtol(p, (char **)&p, 0);
5187 if (cyls < 1 || cyls > 16383)
5192 heads = strtol(p, (char **)&p, 0);
5193 if (heads < 1 || heads > 16)
5198 secs = strtol(p, (char **)&p, 0);
5199 if (secs < 1 || secs > 63)
5203 if (!strcmp(p, "none"))
5204 translation = BIOS_ATA_TRANSLATION_NONE;
5205 else if (!strcmp(p, "lba"))
5206 translation = BIOS_ATA_TRANSLATION_LBA;
5207 else if (!strcmp(p, "auto"))
5208 translation = BIOS_ATA_TRANSLATION_AUTO;
5211 } else if (*p != '\0') {
5213 fprintf(stderr, "qemu: invalid physical CHS format\n");
5218 case QEMU_OPTION_nographic:
5219 pstrcpy(monitor_device, sizeof(monitor_device), "stdio");
5220 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "stdio");
5223 case QEMU_OPTION_kernel:
5224 kernel_filename = optarg;
5226 case QEMU_OPTION_append:
5227 kernel_cmdline = optarg;
5229 case QEMU_OPTION_cdrom:
5230 if (cdrom_index >= 0) {
5231 hd_filename[cdrom_index] = optarg;
5234 case QEMU_OPTION_boot:
5235 boot_device = optarg[0];
5236 if (boot_device != 'a' &&
5239 boot_device != 'n' &&
5241 boot_device != 'c' && boot_device != 'd') {
5242 fprintf(stderr, "qemu: invalid boot device '%c'\n", boot_device);
5246 case QEMU_OPTION_fda:
5247 fd_filename[0] = optarg;
5249 case QEMU_OPTION_fdb:
5250 fd_filename[1] = optarg;
5252 case QEMU_OPTION_no_code_copy:
5253 code_copy_enabled = 0;
5255 case QEMU_OPTION_net:
5256 if (nb_net_clients >= MAX_NET_CLIENTS) {
5257 fprintf(stderr, "qemu: too many network clients\n");
5260 pstrcpy(net_clients[nb_net_clients],
5261 sizeof(net_clients[0]),
5266 case QEMU_OPTION_tftp:
5267 tftp_prefix = optarg;
5270 case QEMU_OPTION_smb:
5271 net_slirp_smb(optarg);
5274 case QEMU_OPTION_redir:
5275 net_slirp_redir(optarg);
5279 case QEMU_OPTION_audio_help:
5283 case QEMU_OPTION_soundhw:
5284 select_soundhw (optarg);
5291 ram_size = atoi(optarg) * 1024 * 1024;
5294 if (ram_size > PHYS_RAM_MAX_SIZE) {
5295 fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
5296 PHYS_RAM_MAX_SIZE / (1024 * 1024));
5305 mask = cpu_str_to_log_mask(optarg);
5307 printf("Log items (comma separated):\n");
5308 for(item = cpu_log_items; item->mask != 0; item++) {
5309 printf("%-10s %s\n", item->name, item->help);
5316 #ifdef CONFIG_GDBSTUB
5321 gdbstub_port = atoi(optarg);
5328 start_emulation = 0;
5331 keyboard_layout = optarg;
5333 case QEMU_OPTION_localtime:
5336 case QEMU_OPTION_cirrusvga:
5337 cirrus_vga_enabled = 1;
5339 case QEMU_OPTION_std_vga:
5340 cirrus_vga_enabled = 0;
5347 w = strtol(p, (char **)&p, 10);
5350 fprintf(stderr, "qemu: invalid resolution or depth\n");
5356 h = strtol(p, (char **)&p, 10);
5361 depth = strtol(p, (char **)&p, 10);
5362 if (depth != 8 && depth != 15 && depth != 16 &&
5363 depth != 24 && depth != 32)
5365 } else if (*p == '\0') {
5366 depth = graphic_depth;
5373 graphic_depth = depth;
5376 case QEMU_OPTION_monitor:
5377 pstrcpy(monitor_device, sizeof(monitor_device), optarg);
5379 case QEMU_OPTION_serial:
5380 if (serial_device_index >= MAX_SERIAL_PORTS) {
5381 fprintf(stderr, "qemu: too many serial ports\n");
5384 pstrcpy(serial_devices[serial_device_index],
5385 sizeof(serial_devices[0]), optarg);
5386 serial_device_index++;
5388 case QEMU_OPTION_parallel:
5389 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
5390 fprintf(stderr, "qemu: too many parallel ports\n");
5393 pstrcpy(parallel_devices[parallel_device_index],
5394 sizeof(parallel_devices[0]), optarg);
5395 parallel_device_index++;
5397 case QEMU_OPTION_loadvm:
5400 case QEMU_OPTION_full_screen:
5403 case QEMU_OPTION_pidfile:
5404 create_pidfile(optarg);
5407 case QEMU_OPTION_win2k_hack:
5408 win2k_install_hack = 1;
5412 case QEMU_OPTION_no_kqemu:
5415 case QEMU_OPTION_kernel_kqemu:
5419 case QEMU_OPTION_usb:
5422 case QEMU_OPTION_usbdevice:
5424 if (usb_devices_index >= MAX_VM_USB_PORTS) {
5425 fprintf(stderr, "Too many USB devices\n");
5428 pstrcpy(usb_devices[usb_devices_index],
5429 sizeof(usb_devices[usb_devices_index]),
5431 usb_devices_index++;
5433 case QEMU_OPTION_smp:
5434 smp_cpus = atoi(optarg);
5435 if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
5436 fprintf(stderr, "Invalid number of CPUs\n");
5440 case QEMU_OPTION_vnc:
5441 vnc_display = atoi(optarg);
5442 if (vnc_display < 0) {
5443 fprintf(stderr, "Invalid VNC display\n");
5455 linux_boot = (kernel_filename != NULL);
5458 hd_filename[0] == '\0' &&
5459 (cdrom_index >= 0 && hd_filename[cdrom_index] == '\0') &&
5460 fd_filename[0] == '\0')
5463 /* boot to cd by default if no hard disk */
5464 if (hd_filename[0] == '\0' && boot_device == 'c') {
5465 if (fd_filename[0] != '\0')
5471 #if !defined(CONFIG_SOFTMMU)
5472 /* must avoid mmap() usage of glibc by setting a buffer "by hand" */
5474 static uint8_t stdout_buf[4096];
5475 setvbuf(stdout, stdout_buf, _IOLBF, sizeof(stdout_buf));
5478 setvbuf(stdout, NULL, _IOLBF, 0);
5485 /* init network clients */
5486 if (nb_net_clients == 0) {
5487 /* if no clients, we use a default config */
5488 pstrcpy(net_clients[0], sizeof(net_clients[0]),
5490 pstrcpy(net_clients[1], sizeof(net_clients[0]),
5495 for(i = 0;i < nb_net_clients; i++) {
5496 if (net_client_init(net_clients[i]) < 0)
5500 /* init the memory */
5501 phys_ram_size = ram_size + vga_ram_size + bios_size;
5503 #ifdef CONFIG_SOFTMMU
5504 phys_ram_base = qemu_vmalloc(phys_ram_size);
5505 if (!phys_ram_base) {
5506 fprintf(stderr, "Could not allocate physical memory\n");
5510 /* as we must map the same page at several addresses, we must use
5515 tmpdir = getenv("QEMU_TMPDIR");
5518 snprintf(phys_ram_file, sizeof(phys_ram_file), "%s/vlXXXXXX", tmpdir);
5519 if (mkstemp(phys_ram_file) < 0) {
5520 fprintf(stderr, "Could not create temporary memory file '%s'\n",
5524 phys_ram_fd = open(phys_ram_file, O_CREAT | O_TRUNC | O_RDWR, 0600);
5525 if (phys_ram_fd < 0) {
5526 fprintf(stderr, "Could not open temporary memory file '%s'\n",
5530 ftruncate(phys_ram_fd, phys_ram_size);
5531 unlink(phys_ram_file);
5532 phys_ram_base = mmap(get_mmap_addr(phys_ram_size),
5534 PROT_WRITE | PROT_READ, MAP_SHARED | MAP_FIXED,
5536 if (phys_ram_base == MAP_FAILED) {
5537 fprintf(stderr, "Could not map physical memory\n");
5543 /* we always create the cdrom drive, even if no disk is there */
5545 if (cdrom_index >= 0) {
5546 bs_table[cdrom_index] = bdrv_new("cdrom");
5547 bdrv_set_type_hint(bs_table[cdrom_index], BDRV_TYPE_CDROM);
5550 /* open the virtual block devices */
5551 for(i = 0; i < MAX_DISKS; i++) {
5552 if (hd_filename[i]) {
5555 snprintf(buf, sizeof(buf), "hd%c", i + 'a');
5556 bs_table[i] = bdrv_new(buf);
5558 if (bdrv_open(bs_table[i], hd_filename[i], snapshot) < 0) {
5559 fprintf(stderr, "qemu: could not open hard disk image '%s'\n",
5563 if (i == 0 && cyls != 0) {
5564 bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
5565 bdrv_set_translation_hint(bs_table[i], translation);
5570 /* we always create at least one floppy disk */
5571 fd_table[0] = bdrv_new("fda");
5572 bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
5574 for(i = 0; i < MAX_FD; i++) {
5575 if (fd_filename[i]) {
5578 snprintf(buf, sizeof(buf), "fd%c", i + 'a');
5579 fd_table[i] = bdrv_new(buf);
5580 bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
5582 if (fd_filename[i] != '\0') {
5583 if (bdrv_open(fd_table[i], fd_filename[i], snapshot) < 0) {
5584 fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
5592 /* init USB devices */
5594 vm_usb_hub = usb_hub_init(vm_usb_ports, MAX_VM_USB_PORTS);
5595 for(i = 0; i < usb_devices_index; i++) {
5596 if (usb_device_add(usb_devices[i]) < 0) {
5597 fprintf(stderr, "Warning: could not add USB device %s\n",
5603 register_savevm("timer", 0, 1, timer_save, timer_load, NULL);
5604 register_savevm("ram", 0, 1, ram_save, ram_load, NULL);
5607 cpu_calibrate_ticks();
5611 dumb_display_init(ds);
5612 } else if (vnc_display != -1) {
5613 vnc_display_init(ds, vnc_display);
5615 #if defined(CONFIG_SDL)
5616 sdl_display_init(ds, full_screen);
5617 #elif defined(CONFIG_COCOA)
5618 cocoa_display_init(ds, full_screen);
5620 dumb_display_init(ds);
5624 monitor_hd = qemu_chr_open(monitor_device);
5626 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
5629 monitor_init(monitor_hd, !nographic);
5631 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5632 if (serial_devices[i][0] != '\0') {
5633 serial_hds[i] = qemu_chr_open(serial_devices[i]);
5634 if (!serial_hds[i]) {
5635 fprintf(stderr, "qemu: could not open serial device '%s'\n",
5639 if (!strcmp(serial_devices[i], "vc"))
5640 qemu_chr_printf(serial_hds[i], "serial%d console\n", i);
5644 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5645 if (parallel_devices[i][0] != '\0') {
5646 parallel_hds[i] = qemu_chr_open(parallel_devices[i]);
5647 if (!parallel_hds[i]) {
5648 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
5649 parallel_devices[i]);
5652 if (!strcmp(parallel_devices[i], "vc"))
5653 qemu_chr_printf(parallel_hds[i], "parallel%d console\n", i);
5657 /* setup cpu signal handlers for MMU / self modifying code handling */
5658 #if !defined(CONFIG_SOFTMMU)
5660 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
5663 signal_stack = memalign(16, SIGNAL_STACK_SIZE);
5664 stk.ss_sp = signal_stack;
5665 stk.ss_size = SIGNAL_STACK_SIZE;
5668 if (sigaltstack(&stk, NULL) < 0) {
5669 perror("sigaltstack");
5675 struct sigaction act;
5677 sigfillset(&act.sa_mask);
5678 act.sa_flags = SA_SIGINFO;
5679 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
5680 act.sa_flags |= SA_ONSTACK;
5682 act.sa_sigaction = host_segv_handler;
5683 sigaction(SIGSEGV, &act, NULL);
5684 sigaction(SIGBUS, &act, NULL);
5685 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
5686 sigaction(SIGFPE, &act, NULL);
5693 struct sigaction act;
5694 sigfillset(&act.sa_mask);
5696 act.sa_handler = SIG_IGN;
5697 sigaction(SIGPIPE, &act, NULL);
5702 machine->init(ram_size, vga_ram_size, boot_device,
5703 ds, fd_filename, snapshot,
5704 kernel_filename, kernel_cmdline, initrd_filename);
5706 gui_timer = qemu_new_timer(rt_clock, gui_update, NULL);
5707 qemu_mod_timer(gui_timer, qemu_get_clock(rt_clock));
5709 #ifdef CONFIG_GDBSTUB
5711 if (gdbserver_start(gdbstub_port) < 0) {
5712 fprintf(stderr, "Could not open gdbserver socket on port %d\n",
5716 printf("Waiting gdb connection on port %d\n", gdbstub_port);
5721 qemu_loadvm(loadvm);
5724 /* XXX: simplify init */
5726 if (start_emulation) {