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>
51 #include <linux/if_tun.h>
54 #include <linux/rtc.h>
55 #include <linux/ppdev.h>
59 #if defined(CONFIG_SLIRP)
65 #include <sys/timeb.h>
67 #define getopt_long_only getopt_long
68 #define memalign(align, size) malloc(size)
75 #endif /* CONFIG_SDL */
79 #define main qemu_main
80 #endif /* CONFIG_COCOA */
86 #define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
88 //#define DEBUG_UNUSED_IOPORT
89 //#define DEBUG_IOPORT
91 #if !defined(CONFIG_SOFTMMU)
92 #define PHYS_RAM_MAX_SIZE (256 * 1024 * 1024)
94 #define PHYS_RAM_MAX_SIZE (2047 * 1024 * 1024)
98 #define DEFAULT_RAM_SIZE 144
100 #define DEFAULT_RAM_SIZE 128
103 #define GUI_REFRESH_INTERVAL 30
105 /* XXX: use a two level table to limit memory usage */
106 #define MAX_IOPORTS 65536
108 const char *bios_dir = CONFIG_QEMU_SHAREDIR;
109 char phys_ram_file[1024];
110 void *ioport_opaque[MAX_IOPORTS];
111 IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
112 IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
113 BlockDriverState *bs_table[MAX_DISKS], *fd_table[MAX_FD];
116 static DisplayState display_state;
118 const char* keyboard_layout = NULL;
119 int64_t ticks_per_sec;
120 int boot_device = 'c';
122 int pit_min_timer_count = 0;
124 NICInfo nd_table[MAX_NICS];
125 QEMUTimer *gui_timer;
128 int cirrus_vga_enabled = 1;
130 int graphic_width = 1024;
131 int graphic_height = 768;
133 int graphic_width = 800;
134 int graphic_height = 600;
136 int graphic_depth = 15;
138 TextConsole *vga_console;
139 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
140 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
142 int win2k_install_hack = 0;
145 USBPort *vm_usb_ports[MAX_VM_USB_PORTS];
146 USBDevice *vm_usb_hub;
147 static VLANState *first_vlan;
149 #if defined(TARGET_SPARC)
151 #elif defined(TARGET_I386)
157 /***********************************************************/
158 /* x86 ISA bus support */
160 target_phys_addr_t isa_mem_base = 0;
163 uint32_t default_ioport_readb(void *opaque, uint32_t address)
165 #ifdef DEBUG_UNUSED_IOPORT
166 fprintf(stderr, "inb: port=0x%04x\n", address);
171 void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
173 #ifdef DEBUG_UNUSED_IOPORT
174 fprintf(stderr, "outb: port=0x%04x data=0x%02x\n", address, data);
178 /* default is to make two byte accesses */
179 uint32_t default_ioport_readw(void *opaque, uint32_t address)
182 data = ioport_read_table[0][address](ioport_opaque[address], address);
183 address = (address + 1) & (MAX_IOPORTS - 1);
184 data |= ioport_read_table[0][address](ioport_opaque[address], address) << 8;
188 void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
190 ioport_write_table[0][address](ioport_opaque[address], address, data & 0xff);
191 address = (address + 1) & (MAX_IOPORTS - 1);
192 ioport_write_table[0][address](ioport_opaque[address], address, (data >> 8) & 0xff);
195 uint32_t default_ioport_readl(void *opaque, uint32_t address)
197 #ifdef DEBUG_UNUSED_IOPORT
198 fprintf(stderr, "inl: port=0x%04x\n", address);
203 void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
205 #ifdef DEBUG_UNUSED_IOPORT
206 fprintf(stderr, "outl: port=0x%04x data=0x%02x\n", address, data);
210 void init_ioports(void)
214 for(i = 0; i < MAX_IOPORTS; i++) {
215 ioport_read_table[0][i] = default_ioport_readb;
216 ioport_write_table[0][i] = default_ioport_writeb;
217 ioport_read_table[1][i] = default_ioport_readw;
218 ioport_write_table[1][i] = default_ioport_writew;
219 ioport_read_table[2][i] = default_ioport_readl;
220 ioport_write_table[2][i] = default_ioport_writel;
224 /* size is the word size in byte */
225 int register_ioport_read(int start, int length, int size,
226 IOPortReadFunc *func, void *opaque)
232 } else if (size == 2) {
234 } else if (size == 4) {
237 hw_error("register_ioport_read: invalid size");
240 for(i = start; i < start + length; i += size) {
241 ioport_read_table[bsize][i] = func;
242 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
243 hw_error("register_ioport_read: invalid opaque");
244 ioport_opaque[i] = opaque;
249 /* size is the word size in byte */
250 int register_ioport_write(int start, int length, int size,
251 IOPortWriteFunc *func, void *opaque)
257 } else if (size == 2) {
259 } else if (size == 4) {
262 hw_error("register_ioport_write: invalid size");
265 for(i = start; i < start + length; i += size) {
266 ioport_write_table[bsize][i] = func;
267 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
268 hw_error("register_ioport_read: invalid opaque");
269 ioport_opaque[i] = opaque;
274 void isa_unassign_ioport(int start, int length)
278 for(i = start; i < start + length; i++) {
279 ioport_read_table[0][i] = default_ioport_readb;
280 ioport_read_table[1][i] = default_ioport_readw;
281 ioport_read_table[2][i] = default_ioport_readl;
283 ioport_write_table[0][i] = default_ioport_writeb;
284 ioport_write_table[1][i] = default_ioport_writew;
285 ioport_write_table[2][i] = default_ioport_writel;
289 /***********************************************************/
291 void pstrcpy(char *buf, int buf_size, const char *str)
301 if (c == 0 || q >= buf + buf_size - 1)
308 /* strcat and truncate. */
309 char *pstrcat(char *buf, int buf_size, const char *s)
314 pstrcpy(buf + len, buf_size - len, s);
318 int strstart(const char *str, const char *val, const char **ptr)
334 /* return the size or -1 if error */
335 int get_image_size(const char *filename)
338 fd = open(filename, O_RDONLY | O_BINARY);
341 size = lseek(fd, 0, SEEK_END);
346 /* return the size or -1 if error */
347 int load_image(const char *filename, uint8_t *addr)
350 fd = open(filename, O_RDONLY | O_BINARY);
353 size = lseek(fd, 0, SEEK_END);
354 lseek(fd, 0, SEEK_SET);
355 if (read(fd, addr, size) != size) {
363 void cpu_outb(CPUState *env, int addr, int val)
366 if (loglevel & CPU_LOG_IOPORT)
367 fprintf(logfile, "outb: %04x %02x\n", addr, val);
369 ioport_write_table[0][addr](ioport_opaque[addr], addr, val);
372 void cpu_outw(CPUState *env, int addr, int val)
375 if (loglevel & CPU_LOG_IOPORT)
376 fprintf(logfile, "outw: %04x %04x\n", addr, val);
378 ioport_write_table[1][addr](ioport_opaque[addr], addr, val);
381 void cpu_outl(CPUState *env, int addr, int val)
384 if (loglevel & CPU_LOG_IOPORT)
385 fprintf(logfile, "outl: %04x %08x\n", addr, val);
387 ioport_write_table[2][addr](ioport_opaque[addr], addr, val);
390 int cpu_inb(CPUState *env, int addr)
393 val = ioport_read_table[0][addr](ioport_opaque[addr], addr);
395 if (loglevel & CPU_LOG_IOPORT)
396 fprintf(logfile, "inb : %04x %02x\n", addr, val);
401 int cpu_inw(CPUState *env, int addr)
404 val = ioport_read_table[1][addr](ioport_opaque[addr], addr);
406 if (loglevel & CPU_LOG_IOPORT)
407 fprintf(logfile, "inw : %04x %04x\n", addr, val);
412 int cpu_inl(CPUState *env, int addr)
415 val = ioport_read_table[2][addr](ioport_opaque[addr], addr);
417 if (loglevel & CPU_LOG_IOPORT)
418 fprintf(logfile, "inl : %04x %08x\n", addr, val);
423 /***********************************************************/
424 void hw_error(const char *fmt, ...)
430 fprintf(stderr, "qemu: hardware error: ");
431 vfprintf(stderr, fmt, ap);
432 fprintf(stderr, "\n");
433 for(env = first_cpu; env != NULL; env = env->next_cpu) {
434 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
436 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
438 cpu_dump_state(env, stderr, fprintf, 0);
445 /***********************************************************/
448 static QEMUPutKBDEvent *qemu_put_kbd_event;
449 static void *qemu_put_kbd_event_opaque;
450 static QEMUPutMouseEvent *qemu_put_mouse_event;
451 static void *qemu_put_mouse_event_opaque;
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)
461 qemu_put_mouse_event_opaque = opaque;
462 qemu_put_mouse_event = func;
465 void kbd_put_keycode(int keycode)
467 if (qemu_put_kbd_event) {
468 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
472 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
474 if (qemu_put_mouse_event) {
475 qemu_put_mouse_event(qemu_put_mouse_event_opaque,
476 dx, dy, dz, buttons_state);
480 /***********************************************************/
483 #if defined(__powerpc__)
485 static inline uint32_t get_tbl(void)
488 asm volatile("mftb %0" : "=r" (tbl));
492 static inline uint32_t get_tbu(void)
495 asm volatile("mftbu %0" : "=r" (tbl));
499 int64_t cpu_get_real_ticks(void)
502 /* NOTE: we test if wrapping has occurred */
508 return ((int64_t)h << 32) | l;
511 #elif defined(__i386__)
513 int64_t cpu_get_real_ticks(void)
516 asm volatile ("rdtsc" : "=A" (val));
520 #elif defined(__x86_64__)
522 int64_t cpu_get_real_ticks(void)
526 asm volatile("rdtsc" : "=a" (low), "=d" (high));
533 #elif defined(__ia64)
535 int64_t cpu_get_real_ticks(void)
538 asm volatile ("mov %0 = ar.itc" : "=r"(val) :: "memory");
542 #elif defined(__s390__)
544 int64_t cpu_get_real_ticks(void)
547 asm volatile("stck 0(%1)" : "=m" (val) : "a" (&val) : "cc");
552 #error unsupported CPU
555 static int64_t cpu_ticks_offset;
556 static int cpu_ticks_enabled;
558 static inline int64_t cpu_get_ticks(void)
560 if (!cpu_ticks_enabled) {
561 return cpu_ticks_offset;
563 return cpu_get_real_ticks() + cpu_ticks_offset;
567 /* enable cpu_get_ticks() */
568 void cpu_enable_ticks(void)
570 if (!cpu_ticks_enabled) {
571 cpu_ticks_offset -= cpu_get_real_ticks();
572 cpu_ticks_enabled = 1;
576 /* disable cpu_get_ticks() : the clock is stopped. You must not call
577 cpu_get_ticks() after that. */
578 void cpu_disable_ticks(void)
580 if (cpu_ticks_enabled) {
581 cpu_ticks_offset = cpu_get_ticks();
582 cpu_ticks_enabled = 0;
586 static int64_t get_clock(void)
591 return ((int64_t)tb.time * 1000 + (int64_t)tb.millitm) * 1000;
594 gettimeofday(&tv, NULL);
595 return tv.tv_sec * 1000000LL + tv.tv_usec;
599 void cpu_calibrate_ticks(void)
604 ticks = cpu_get_real_ticks();
610 usec = get_clock() - usec;
611 ticks = cpu_get_real_ticks() - ticks;
612 ticks_per_sec = (ticks * 1000000LL + (usec >> 1)) / usec;
615 /* compute with 96 bit intermediate result: (a*b)/c */
616 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
621 #ifdef WORDS_BIGENDIAN
631 rl = (uint64_t)u.l.low * (uint64_t)b;
632 rh = (uint64_t)u.l.high * (uint64_t)b;
635 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
639 #define QEMU_TIMER_REALTIME 0
640 #define QEMU_TIMER_VIRTUAL 1
644 /* XXX: add frequency */
652 struct QEMUTimer *next;
658 static QEMUTimer *active_timers[2];
660 static MMRESULT timerID;
662 /* frequency of the times() clock tick */
663 static int timer_freq;
666 QEMUClock *qemu_new_clock(int type)
669 clock = qemu_mallocz(sizeof(QEMUClock));
676 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
680 ts = qemu_mallocz(sizeof(QEMUTimer));
687 void qemu_free_timer(QEMUTimer *ts)
692 /* stop a timer, but do not dealloc it */
693 void qemu_del_timer(QEMUTimer *ts)
697 /* NOTE: this code must be signal safe because
698 qemu_timer_expired() can be called from a signal. */
699 pt = &active_timers[ts->clock->type];
712 /* modify the current timer so that it will be fired when current_time
713 >= expire_time. The corresponding callback will be called. */
714 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
720 /* add the timer in the sorted list */
721 /* NOTE: this code must be signal safe because
722 qemu_timer_expired() can be called from a signal. */
723 pt = &active_timers[ts->clock->type];
728 if (t->expire_time > expire_time)
732 ts->expire_time = expire_time;
737 int qemu_timer_pending(QEMUTimer *ts)
740 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
747 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
751 return (timer_head->expire_time <= current_time);
754 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
760 if (!ts || ts->expire_time > current_time)
762 /* remove timer from the list before calling the callback */
763 *ptimer_head = ts->next;
766 /* run the callback (the timer list can be modified) */
771 int64_t qemu_get_clock(QEMUClock *clock)
773 switch(clock->type) {
774 case QEMU_TIMER_REALTIME:
776 return GetTickCount();
781 /* Note that using gettimeofday() is not a good solution
782 for timers because its value change when the date is
784 if (timer_freq == 100) {
785 return times(&tp) * 10;
787 return ((int64_t)times(&tp) * 1000) / timer_freq;
792 case QEMU_TIMER_VIRTUAL:
793 return cpu_get_ticks();
798 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
800 uint64_t expire_time;
802 if (qemu_timer_pending(ts)) {
803 expire_time = ts->expire_time;
807 qemu_put_be64(f, expire_time);
810 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
812 uint64_t expire_time;
814 expire_time = qemu_get_be64(f);
815 if (expire_time != -1) {
816 qemu_mod_timer(ts, expire_time);
822 static void timer_save(QEMUFile *f, void *opaque)
824 if (cpu_ticks_enabled) {
825 hw_error("cannot save state if virtual timers are running");
827 qemu_put_be64s(f, &cpu_ticks_offset);
828 qemu_put_be64s(f, &ticks_per_sec);
831 static int timer_load(QEMUFile *f, void *opaque, int version_id)
835 if (cpu_ticks_enabled) {
838 qemu_get_be64s(f, &cpu_ticks_offset);
839 qemu_get_be64s(f, &ticks_per_sec);
844 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
845 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
847 static void host_alarm_handler(int host_signum)
851 #define DISP_FREQ 1000
853 static int64_t delta_min = INT64_MAX;
854 static int64_t delta_max, delta_cum, last_clock, delta, ti;
856 ti = qemu_get_clock(vm_clock);
857 if (last_clock != 0) {
858 delta = ti - last_clock;
859 if (delta < delta_min)
861 if (delta > delta_max)
864 if (++count == DISP_FREQ) {
865 printf("timer: min=%lld us max=%lld us avg=%lld us avg_freq=%0.3f Hz\n",
866 muldiv64(delta_min, 1000000, ticks_per_sec),
867 muldiv64(delta_max, 1000000, ticks_per_sec),
868 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
869 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
871 delta_min = INT64_MAX;
879 if (qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
880 qemu_get_clock(vm_clock)) ||
881 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
882 qemu_get_clock(rt_clock))) {
883 CPUState *env = cpu_single_env;
885 /* stop the currently executing cpu because a timer occured */
886 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
888 if (env->kqemu_enabled) {
889 kqemu_cpu_interrupt(env);
898 #if defined(__linux__)
900 #define RTC_FREQ 1024
904 static int start_rtc_timer(void)
906 rtc_fd = open("/dev/rtc", O_RDONLY);
909 if (ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
910 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
911 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
912 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
915 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
920 pit_min_timer_count = PIT_FREQ / RTC_FREQ;
926 static int start_rtc_timer(void)
931 #endif /* !defined(__linux__) */
933 #endif /* !defined(_WIN32) */
935 static void init_timers(void)
937 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
938 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
943 timerID = timeSetEvent(1, // interval (ms)
945 host_alarm_handler, // function
946 (DWORD)&count, // user parameter
947 TIME_PERIODIC | TIME_CALLBACK_FUNCTION);
949 perror("failed timer alarm");
953 pit_min_timer_count = ((uint64_t)10000 * PIT_FREQ) / 1000000;
956 struct sigaction act;
957 struct itimerval itv;
959 /* get times() syscall frequency */
960 timer_freq = sysconf(_SC_CLK_TCK);
963 sigfillset(&act.sa_mask);
965 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
966 act.sa_flags |= SA_ONSTACK;
968 act.sa_handler = host_alarm_handler;
969 sigaction(SIGALRM, &act, NULL);
971 itv.it_interval.tv_sec = 0;
972 itv.it_interval.tv_usec = 999; /* for i386 kernel 2.6 to get 1 ms */
973 itv.it_value.tv_sec = 0;
974 itv.it_value.tv_usec = 10 * 1000;
975 setitimer(ITIMER_REAL, &itv, NULL);
976 /* we probe the tick duration of the kernel to inform the user if
977 the emulated kernel requested a too high timer frequency */
978 getitimer(ITIMER_REAL, &itv);
980 #if defined(__linux__)
981 if (itv.it_interval.tv_usec > 1000) {
982 /* try to use /dev/rtc to have a faster timer */
983 if (start_rtc_timer() < 0)
986 itv.it_interval.tv_sec = 0;
987 itv.it_interval.tv_usec = 0;
988 itv.it_value.tv_sec = 0;
989 itv.it_value.tv_usec = 0;
990 setitimer(ITIMER_REAL, &itv, NULL);
993 sigaction(SIGIO, &act, NULL);
994 fcntl(rtc_fd, F_SETFL, O_ASYNC);
995 fcntl(rtc_fd, F_SETOWN, getpid());
997 #endif /* defined(__linux__) */
1000 pit_min_timer_count = ((uint64_t)itv.it_interval.tv_usec *
1001 PIT_FREQ) / 1000000;
1007 void quit_timers(void)
1010 timeKillEvent(timerID);
1014 /***********************************************************/
1015 /* character device */
1017 int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1019 return s->chr_write(s, buf, len);
1022 int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1026 return s->chr_ioctl(s, cmd, arg);
1029 void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1034 vsnprintf(buf, sizeof(buf), fmt, ap);
1035 qemu_chr_write(s, buf, strlen(buf));
1039 void qemu_chr_send_event(CharDriverState *s, int event)
1041 if (s->chr_send_event)
1042 s->chr_send_event(s, event);
1045 void qemu_chr_add_read_handler(CharDriverState *s,
1046 IOCanRWHandler *fd_can_read,
1047 IOReadHandler *fd_read, void *opaque)
1049 s->chr_add_read_handler(s, fd_can_read, fd_read, opaque);
1052 void qemu_chr_add_event_handler(CharDriverState *s, IOEventHandler *chr_event)
1054 s->chr_event = chr_event;
1057 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1062 static void null_chr_add_read_handler(CharDriverState *chr,
1063 IOCanRWHandler *fd_can_read,
1064 IOReadHandler *fd_read, void *opaque)
1068 CharDriverState *qemu_chr_open_null(void)
1070 CharDriverState *chr;
1072 chr = qemu_mallocz(sizeof(CharDriverState));
1075 chr->chr_write = null_chr_write;
1076 chr->chr_add_read_handler = null_chr_add_read_handler;
1084 IOCanRWHandler *fd_can_read;
1085 IOReadHandler *fd_read;
1090 #define STDIO_MAX_CLIENTS 2
1092 static int stdio_nb_clients;
1093 static CharDriverState *stdio_clients[STDIO_MAX_CLIENTS];
1095 static int unix_write(int fd, const uint8_t *buf, int len1)
1101 ret = write(fd, buf, len);
1103 if (errno != EINTR && errno != EAGAIN)
1105 } else if (ret == 0) {
1115 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1117 FDCharDriver *s = chr->opaque;
1118 return unix_write(s->fd_out, buf, len);
1121 static int fd_chr_read_poll(void *opaque)
1123 CharDriverState *chr = opaque;
1124 FDCharDriver *s = chr->opaque;
1126 s->max_size = s->fd_can_read(s->fd_opaque);
1130 static void fd_chr_read(void *opaque)
1132 CharDriverState *chr = opaque;
1133 FDCharDriver *s = chr->opaque;
1138 if (len > s->max_size)
1142 size = read(s->fd_in, buf, len);
1144 s->fd_read(s->fd_opaque, buf, size);
1148 static void fd_chr_add_read_handler(CharDriverState *chr,
1149 IOCanRWHandler *fd_can_read,
1150 IOReadHandler *fd_read, void *opaque)
1152 FDCharDriver *s = chr->opaque;
1154 if (s->fd_in >= 0) {
1155 s->fd_can_read = fd_can_read;
1156 s->fd_read = fd_read;
1157 s->fd_opaque = opaque;
1158 if (nographic && s->fd_in == 0) {
1160 qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
1161 fd_chr_read, NULL, chr);
1166 /* open a character device to a unix fd */
1167 CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
1169 CharDriverState *chr;
1172 chr = qemu_mallocz(sizeof(CharDriverState));
1175 s = qemu_mallocz(sizeof(FDCharDriver));
1183 chr->chr_write = fd_chr_write;
1184 chr->chr_add_read_handler = fd_chr_add_read_handler;
1188 CharDriverState *qemu_chr_open_file_out(const char *file_out)
1192 fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY);
1195 return qemu_chr_open_fd(-1, fd_out);
1198 CharDriverState *qemu_chr_open_pipe(const char *filename)
1202 fd = open(filename, O_RDWR | O_BINARY);
1205 return qemu_chr_open_fd(fd, fd);
1209 /* for STDIO, we handle the case where several clients use it
1212 #define TERM_ESCAPE 0x01 /* ctrl-a is used for escape */
1214 #define TERM_FIFO_MAX_SIZE 1
1216 static int term_got_escape, client_index;
1217 static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
1220 void term_print_help(void)
1223 "C-a h print this help\n"
1224 "C-a x exit emulator\n"
1225 "C-a s save disk data back to file (if -snapshot)\n"
1226 "C-a b send break (magic sysrq)\n"
1227 "C-a c switch between console and monitor\n"
1228 "C-a C-a send C-a\n"
1232 /* called when a char is received */
1233 static void stdio_received_byte(int ch)
1235 if (term_got_escape) {
1236 term_got_escape = 0;
1247 for (i = 0; i < MAX_DISKS; i++) {
1249 bdrv_commit(bs_table[i]);
1254 if (client_index < stdio_nb_clients) {
1255 CharDriverState *chr;
1258 chr = stdio_clients[client_index];
1260 chr->chr_event(s->fd_opaque, CHR_EVENT_BREAK);
1265 if (client_index >= stdio_nb_clients)
1267 if (client_index == 0) {
1268 /* send a new line in the monitor to get the prompt */
1276 } else if (ch == TERM_ESCAPE) {
1277 term_got_escape = 1;
1280 if (client_index < stdio_nb_clients) {
1282 CharDriverState *chr;
1285 chr = stdio_clients[client_index];
1287 if (s->fd_can_read(s->fd_opaque) > 0) {
1289 s->fd_read(s->fd_opaque, buf, 1);
1290 } else if (term_fifo_size == 0) {
1291 term_fifo[term_fifo_size++] = ch;
1297 static int stdio_read_poll(void *opaque)
1299 CharDriverState *chr;
1302 if (client_index < stdio_nb_clients) {
1303 chr = stdio_clients[client_index];
1305 /* try to flush the queue if needed */
1306 if (term_fifo_size != 0 && s->fd_can_read(s->fd_opaque) > 0) {
1307 s->fd_read(s->fd_opaque, term_fifo, 1);
1310 /* see if we can absorb more chars */
1311 if (term_fifo_size == 0)
1320 static void stdio_read(void *opaque)
1325 size = read(0, buf, 1);
1327 stdio_received_byte(buf[0]);
1330 /* init terminal so that we can grab keys */
1331 static struct termios oldtty;
1332 static int old_fd0_flags;
1334 static void term_exit(void)
1336 tcsetattr (0, TCSANOW, &oldtty);
1337 fcntl(0, F_SETFL, old_fd0_flags);
1340 static void term_init(void)
1344 tcgetattr (0, &tty);
1346 old_fd0_flags = fcntl(0, F_GETFL);
1348 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1349 |INLCR|IGNCR|ICRNL|IXON);
1350 tty.c_oflag |= OPOST;
1351 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1352 /* if graphical mode, we allow Ctrl-C handling */
1354 tty.c_lflag &= ~ISIG;
1355 tty.c_cflag &= ~(CSIZE|PARENB);
1358 tty.c_cc[VTIME] = 0;
1360 tcsetattr (0, TCSANOW, &tty);
1364 fcntl(0, F_SETFL, O_NONBLOCK);
1367 CharDriverState *qemu_chr_open_stdio(void)
1369 CharDriverState *chr;
1372 if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
1374 chr = qemu_chr_open_fd(0, 1);
1375 if (stdio_nb_clients == 0)
1376 qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, NULL);
1377 client_index = stdio_nb_clients;
1379 if (stdio_nb_clients != 0)
1381 chr = qemu_chr_open_fd(0, 1);
1383 stdio_clients[stdio_nb_clients++] = chr;
1384 if (stdio_nb_clients == 1) {
1385 /* set the terminal in raw mode */
1391 #if defined(__linux__)
1392 CharDriverState *qemu_chr_open_pty(void)
1395 char slave_name[1024];
1396 int master_fd, slave_fd;
1398 /* Not satisfying */
1399 if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
1403 /* Disabling local echo and line-buffered output */
1404 tcgetattr (master_fd, &tty);
1405 tty.c_lflag &= ~(ECHO|ICANON|ISIG);
1407 tty.c_cc[VTIME] = 0;
1408 tcsetattr (master_fd, TCSAFLUSH, &tty);
1410 fprintf(stderr, "char device redirected to %s\n", slave_name);
1411 return qemu_chr_open_fd(master_fd, master_fd);
1414 static void tty_serial_init(int fd, int speed,
1415 int parity, int data_bits, int stop_bits)
1421 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1422 speed, parity, data_bits, stop_bits);
1424 tcgetattr (fd, &tty);
1466 cfsetispeed(&tty, spd);
1467 cfsetospeed(&tty, spd);
1469 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1470 |INLCR|IGNCR|ICRNL|IXON);
1471 tty.c_oflag |= OPOST;
1472 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1473 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS);
1494 tty.c_cflag |= PARENB;
1497 tty.c_cflag |= PARENB | PARODD;
1501 tcsetattr (fd, TCSANOW, &tty);
1504 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1506 FDCharDriver *s = chr->opaque;
1509 case CHR_IOCTL_SERIAL_SET_PARAMS:
1511 QEMUSerialSetParams *ssp = arg;
1512 tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
1513 ssp->data_bits, ssp->stop_bits);
1516 case CHR_IOCTL_SERIAL_SET_BREAK:
1518 int enable = *(int *)arg;
1520 tcsendbreak(s->fd_in, 1);
1529 CharDriverState *qemu_chr_open_tty(const char *filename)
1531 CharDriverState *chr;
1534 fd = open(filename, O_RDWR | O_NONBLOCK);
1537 fcntl(fd, F_SETFL, O_NONBLOCK);
1538 tty_serial_init(fd, 115200, 'N', 8, 1);
1539 chr = qemu_chr_open_fd(fd, fd);
1542 chr->chr_ioctl = tty_serial_ioctl;
1546 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1548 int fd = (int)chr->opaque;
1552 case CHR_IOCTL_PP_READ_DATA:
1553 if (ioctl(fd, PPRDATA, &b) < 0)
1555 *(uint8_t *)arg = b;
1557 case CHR_IOCTL_PP_WRITE_DATA:
1558 b = *(uint8_t *)arg;
1559 if (ioctl(fd, PPWDATA, &b) < 0)
1562 case CHR_IOCTL_PP_READ_CONTROL:
1563 if (ioctl(fd, PPRCONTROL, &b) < 0)
1565 *(uint8_t *)arg = b;
1567 case CHR_IOCTL_PP_WRITE_CONTROL:
1568 b = *(uint8_t *)arg;
1569 if (ioctl(fd, PPWCONTROL, &b) < 0)
1572 case CHR_IOCTL_PP_READ_STATUS:
1573 if (ioctl(fd, PPRSTATUS, &b) < 0)
1575 *(uint8_t *)arg = b;
1583 CharDriverState *qemu_chr_open_pp(const char *filename)
1585 CharDriverState *chr;
1588 fd = open(filename, O_RDWR);
1592 if (ioctl(fd, PPCLAIM) < 0) {
1597 chr = qemu_mallocz(sizeof(CharDriverState));
1602 chr->opaque = (void *)fd;
1603 chr->chr_write = null_chr_write;
1604 chr->chr_add_read_handler = null_chr_add_read_handler;
1605 chr->chr_ioctl = pp_ioctl;
1610 CharDriverState *qemu_chr_open_pty(void)
1616 #endif /* !defined(_WIN32) */
1618 CharDriverState *qemu_chr_open(const char *filename)
1621 if (!strcmp(filename, "vc")) {
1622 return text_console_init(&display_state);
1623 } else if (!strcmp(filename, "null")) {
1624 return qemu_chr_open_null();
1627 if (strstart(filename, "file:", &p)) {
1628 return qemu_chr_open_file_out(p);
1629 } else if (strstart(filename, "pipe:", &p)) {
1630 return qemu_chr_open_pipe(p);
1631 } else if (!strcmp(filename, "pty")) {
1632 return qemu_chr_open_pty();
1633 } else if (!strcmp(filename, "stdio")) {
1634 return qemu_chr_open_stdio();
1637 #if defined(__linux__)
1638 if (strstart(filename, "/dev/parport", NULL)) {
1639 return qemu_chr_open_pp(filename);
1641 if (strstart(filename, "/dev/", NULL)) {
1642 return qemu_chr_open_tty(filename);
1650 /***********************************************************/
1651 /* network device redirectors */
1653 void hex_dump(FILE *f, const uint8_t *buf, int size)
1657 for(i=0;i<size;i+=16) {
1661 fprintf(f, "%08x ", i);
1664 fprintf(f, " %02x", buf[i+j]);
1669 for(j=0;j<len;j++) {
1671 if (c < ' ' || c > '~')
1673 fprintf(f, "%c", c);
1679 static int parse_macaddr(uint8_t *macaddr, const char *p)
1682 for(i = 0; i < 6; i++) {
1683 macaddr[i] = strtol(p, (char **)&p, 16);
1696 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
1701 p1 = strchr(p, sep);
1707 if (len > buf_size - 1)
1709 memcpy(buf, p, len);
1716 int parse_host_port(struct sockaddr_in *saddr, const char *str)
1724 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
1726 saddr->sin_family = AF_INET;
1727 if (buf[0] == '\0') {
1728 saddr->sin_addr.s_addr = 0;
1730 if (isdigit(buf[0])) {
1731 if (!inet_aton(buf, &saddr->sin_addr))
1737 if ((he = gethostbyname(buf)) == NULL)
1739 saddr->sin_addr = *(struct in_addr *)he->h_addr;
1743 port = strtol(p, (char **)&r, 0);
1746 saddr->sin_port = htons(port);
1750 /* find or alloc a new VLAN */
1751 VLANState *qemu_find_vlan(int id)
1753 VLANState **pvlan, *vlan;
1754 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
1758 vlan = qemu_mallocz(sizeof(VLANState));
1763 pvlan = &first_vlan;
1764 while (*pvlan != NULL)
1765 pvlan = &(*pvlan)->next;
1770 VLANClientState *qemu_new_vlan_client(VLANState *vlan,
1771 IOReadHandler *fd_read, void *opaque)
1773 VLANClientState *vc, **pvc;
1774 vc = qemu_mallocz(sizeof(VLANClientState));
1777 vc->fd_read = fd_read;
1778 vc->opaque = opaque;
1782 pvc = &vlan->first_client;
1783 while (*pvc != NULL)
1784 pvc = &(*pvc)->next;
1789 void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
1791 VLANState *vlan = vc1->vlan;
1792 VLANClientState *vc;
1795 printf("vlan %d send:\n", vlan->id);
1796 hex_dump(stdout, buf, size);
1798 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
1800 vc->fd_read(vc->opaque, buf, size);
1805 #if defined(CONFIG_SLIRP)
1807 /* slirp network adapter */
1809 static int slirp_inited;
1810 static VLANClientState *slirp_vc;
1812 int slirp_can_output(void)
1817 void slirp_output(const uint8_t *pkt, int pkt_len)
1820 printf("slirp output:\n");
1821 hex_dump(stdout, pkt, pkt_len);
1823 qemu_send_packet(slirp_vc, pkt, pkt_len);
1826 static void slirp_receive(void *opaque, const uint8_t *buf, int size)
1829 printf("slirp input:\n");
1830 hex_dump(stdout, buf, size);
1832 slirp_input(buf, size);
1835 static int net_slirp_init(VLANState *vlan)
1837 if (!slirp_inited) {
1841 slirp_vc = qemu_new_vlan_client(vlan,
1842 slirp_receive, NULL);
1843 snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
1847 static void net_slirp_redir(const char *redir_str)
1852 struct in_addr guest_addr;
1853 int host_port, guest_port;
1855 if (!slirp_inited) {
1861 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
1863 if (!strcmp(buf, "tcp")) {
1865 } else if (!strcmp(buf, "udp")) {
1871 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
1873 host_port = strtol(buf, &r, 0);
1877 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
1879 if (buf[0] == '\0') {
1880 pstrcpy(buf, sizeof(buf), "10.0.2.15");
1882 if (!inet_aton(buf, &guest_addr))
1885 guest_port = strtol(p, &r, 0);
1889 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
1890 fprintf(stderr, "qemu: could not set up redirection\n");
1895 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
1903 static void smb_exit(void)
1907 char filename[1024];
1909 /* erase all the files in the directory */
1910 d = opendir(smb_dir);
1915 if (strcmp(de->d_name, ".") != 0 &&
1916 strcmp(de->d_name, "..") != 0) {
1917 snprintf(filename, sizeof(filename), "%s/%s",
1918 smb_dir, de->d_name);
1926 /* automatic user mode samba server configuration */
1927 void net_slirp_smb(const char *exported_dir)
1929 char smb_conf[1024];
1930 char smb_cmdline[1024];
1933 if (!slirp_inited) {
1938 /* XXX: better tmp dir construction */
1939 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
1940 if (mkdir(smb_dir, 0700) < 0) {
1941 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
1944 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
1946 f = fopen(smb_conf, "w");
1948 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
1955 "socket address=127.0.0.1\n"
1956 "pid directory=%s\n"
1957 "lock directory=%s\n"
1958 "log file=%s/log.smbd\n"
1959 "smb passwd file=%s/smbpasswd\n"
1960 "security = share\n"
1975 snprintf(smb_cmdline, sizeof(smb_cmdline), "/usr/sbin/smbd -s %s",
1978 slirp_add_exec(0, smb_cmdline, 4, 139);
1981 #endif /* !defined(_WIN32) */
1983 #endif /* CONFIG_SLIRP */
1985 #if !defined(_WIN32)
1987 typedef struct TAPState {
1988 VLANClientState *vc;
1992 static void tap_receive(void *opaque, const uint8_t *buf, int size)
1994 TAPState *s = opaque;
1997 ret = write(s->fd, buf, size);
1998 if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
2005 static void tap_send(void *opaque)
2007 TAPState *s = opaque;
2011 size = read(s->fd, buf, sizeof(buf));
2013 qemu_send_packet(s->vc, buf, size);
2019 static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
2023 s = qemu_mallocz(sizeof(TAPState));
2027 s->vc = qemu_new_vlan_client(vlan, tap_receive, s);
2028 qemu_set_fd_handler(s->fd, tap_send, NULL, s);
2029 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
2034 static int tap_open(char *ifname, int ifname_size)
2040 fd = open("/dev/tap", O_RDWR);
2042 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
2047 dev = devname(s.st_rdev, S_IFCHR);
2048 pstrcpy(ifname, ifname_size, dev);
2050 fcntl(fd, F_SETFL, O_NONBLOCK);
2054 static int tap_open(char *ifname, int ifname_size)
2059 fd = open("/dev/net/tun", O_RDWR);
2061 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
2064 memset(&ifr, 0, sizeof(ifr));
2065 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
2066 if (ifname[0] != '\0')
2067 pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
2069 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
2070 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
2072 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
2076 pstrcpy(ifname, ifname_size, ifr.ifr_name);
2077 fcntl(fd, F_SETFL, O_NONBLOCK);
2082 static int net_tap_init(VLANState *vlan, const char *ifname1,
2083 const char *setup_script)
2086 int pid, status, fd;
2091 if (ifname1 != NULL)
2092 pstrcpy(ifname, sizeof(ifname), ifname1);
2095 fd = tap_open(ifname, sizeof(ifname));
2101 if (setup_script[0] != '\0') {
2102 /* try to launch network init script */
2107 *parg++ = (char *)setup_script;
2110 execv(setup_script, args);
2113 while (waitpid(pid, &status, 0) != pid);
2114 if (!WIFEXITED(status) ||
2115 WEXITSTATUS(status) != 0) {
2116 fprintf(stderr, "%s: could not launch network script\n",
2122 s = net_tap_fd_init(vlan, fd);
2125 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
2126 "tap: ifname=%s setup_script=%s", ifname, setup_script);
2130 /* network connection */
2131 typedef struct NetSocketState {
2132 VLANClientState *vc;
2134 int state; /* 0 = getting length, 1 = getting data */
2138 struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
2141 typedef struct NetSocketListenState {
2144 } NetSocketListenState;
2146 /* XXX: we consider we can send the whole packet without blocking */
2147 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
2149 NetSocketState *s = opaque;
2153 unix_write(s->fd, (const uint8_t *)&len, sizeof(len));
2154 unix_write(s->fd, buf, size);
2157 static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
2159 NetSocketState *s = opaque;
2160 sendto(s->fd, buf, size, 0,
2161 (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
2164 static void net_socket_send(void *opaque)
2166 NetSocketState *s = opaque;
2171 size = read(s->fd, buf1, sizeof(buf1));
2175 /* end of connection */
2176 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2181 /* reassemble a packet from the network */
2187 memcpy(s->buf + s->index, buf, l);
2191 if (s->index == 4) {
2193 s->packet_len = ntohl(*(uint32_t *)s->buf);
2199 l = s->packet_len - s->index;
2202 memcpy(s->buf + s->index, buf, l);
2206 if (s->index >= s->packet_len) {
2207 qemu_send_packet(s->vc, s->buf, s->packet_len);
2216 static void net_socket_send_dgram(void *opaque)
2218 NetSocketState *s = opaque;
2221 size = recv(s->fd, s->buf, sizeof(s->buf), 0);
2225 /* end of connection */
2226 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2229 qemu_send_packet(s->vc, s->buf, size);
2232 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
2237 if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
2238 fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
2239 inet_ntoa(mcastaddr->sin_addr), ntohl(mcastaddr->sin_addr.s_addr));
2243 fd = socket(PF_INET, SOCK_DGRAM, 0);
2245 perror("socket(PF_INET, SOCK_DGRAM)");
2249 /* Add host to multicast group */
2250 imr.imr_multiaddr = mcastaddr->sin_addr;
2251 imr.imr_interface.s_addr = htonl(INADDR_ANY);
2253 ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP, (void *) &imr, sizeof(struct ip_mreq));
2255 perror("setsockopt(IP_ADD_MEMBERSHIP)");
2259 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
2261 ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP, &val, sizeof(val));
2263 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
2267 ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val));
2269 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
2273 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
2279 fcntl(fd, F_SETFL, O_NONBLOCK);
2282 if (fd>=0) close(fd);
2286 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd,
2289 struct sockaddr_in saddr;
2291 socklen_t saddr_len;
2294 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
2295 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
2296 * by ONLY ONE process: we must "clone" this dgram socket --jjo
2300 if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
2302 if (saddr.sin_addr.s_addr==0) {
2303 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
2307 /* clone dgram socket */
2308 newfd = net_socket_mcast_create(&saddr);
2310 /* error already reported by net_socket_mcast_create() */
2314 /* clone newfd to fd, close newfd */
2319 fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
2320 fd, strerror(errno));
2325 s = qemu_mallocz(sizeof(NetSocketState));
2330 s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, s);
2331 qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
2333 /* mcast: save bound address as dst */
2334 if (is_connected) s->dgram_dst=saddr;
2336 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
2337 "socket: fd=%d (%s mcast=%s:%d)",
2338 fd, is_connected? "cloned" : "",
2339 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
2343 static void net_socket_connect(void *opaque)
2345 NetSocketState *s = opaque;
2346 qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
2349 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd,
2353 s = qemu_mallocz(sizeof(NetSocketState));
2357 s->vc = qemu_new_vlan_client(vlan,
2358 net_socket_receive, s);
2359 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
2360 "socket: fd=%d", fd);
2362 net_socket_connect(s);
2364 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
2369 static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
2372 int so_type=-1, optlen=sizeof(so_type);
2374 if(getsockopt(fd, SOL_SOCKET,SO_TYPE, &so_type, &optlen)< 0) {
2375 fprintf(stderr, "qemu: error: setsockopt(SO_TYPE) for fd=%d failed\n", fd);
2380 return net_socket_fd_init_dgram(vlan, fd, is_connected);
2382 return net_socket_fd_init_stream(vlan, fd, is_connected);
2384 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
2385 fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
2386 return net_socket_fd_init_stream(vlan, fd, is_connected);
2391 static void net_socket_accept(void *opaque)
2393 NetSocketListenState *s = opaque;
2395 struct sockaddr_in saddr;
2400 len = sizeof(saddr);
2401 fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
2402 if (fd < 0 && errno != EINTR) {
2404 } else if (fd >= 0) {
2408 s1 = net_socket_fd_init(s->vlan, fd, 1);
2412 snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
2413 "socket: connection from %s:%d",
2414 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
2418 static int net_socket_listen_init(VLANState *vlan, const char *host_str)
2420 NetSocketListenState *s;
2422 struct sockaddr_in saddr;
2424 if (parse_host_port(&saddr, host_str) < 0)
2427 s = qemu_mallocz(sizeof(NetSocketListenState));
2431 fd = socket(PF_INET, SOCK_STREAM, 0);
2436 fcntl(fd, F_SETFL, O_NONBLOCK);
2438 /* allow fast reuse */
2440 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val));
2442 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
2447 ret = listen(fd, 0);
2454 qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
2458 static int net_socket_connect_init(VLANState *vlan, const char *host_str)
2461 int fd, connected, ret;
2462 struct sockaddr_in saddr;
2464 if (parse_host_port(&saddr, host_str) < 0)
2467 fd = socket(PF_INET, SOCK_STREAM, 0);
2472 fcntl(fd, F_SETFL, O_NONBLOCK);
2476 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
2478 if (errno == EINTR || errno == EAGAIN) {
2479 } else if (errno == EINPROGRESS) {
2491 s = net_socket_fd_init(vlan, fd, connected);
2494 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
2495 "socket: connect to %s:%d",
2496 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
2500 static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
2504 struct sockaddr_in saddr;
2506 if (parse_host_port(&saddr, host_str) < 0)
2510 fd = net_socket_mcast_create(&saddr);
2514 s = net_socket_fd_init(vlan, fd, 0);
2518 s->dgram_dst = saddr;
2520 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
2521 "socket: mcast=%s:%d",
2522 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
2527 #endif /* !_WIN32 */
2529 static int get_param_value(char *buf, int buf_size,
2530 const char *tag, const char *str)
2539 while (*p != '\0' && *p != '=') {
2540 if ((q - option) < sizeof(option) - 1)
2548 if (!strcmp(tag, option)) {
2550 while (*p != '\0' && *p != ',') {
2551 if ((q - buf) < buf_size - 1)
2558 while (*p != '\0' && *p != ',') {
2569 int net_client_init(const char *str)
2580 while (*p != '\0' && *p != ',') {
2581 if ((q - device) < sizeof(device) - 1)
2589 if (get_param_value(buf, sizeof(buf), "vlan", p)) {
2590 vlan_id = strtol(buf, NULL, 0);
2592 vlan = qemu_find_vlan(vlan_id);
2594 fprintf(stderr, "Could not create vlan %d\n", vlan_id);
2597 if (!strcmp(device, "nic")) {
2601 if (nb_nics >= MAX_NICS) {
2602 fprintf(stderr, "Too Many NICs\n");
2605 nd = &nd_table[nb_nics];
2606 macaddr = nd->macaddr;
2612 macaddr[5] = 0x56 + nb_nics;
2614 if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
2615 if (parse_macaddr(macaddr, buf) < 0) {
2616 fprintf(stderr, "invalid syntax for ethernet address\n");
2624 if (!strcmp(device, "none")) {
2625 /* does nothing. It is needed to signal that no network cards
2630 if (!strcmp(device, "user")) {
2631 ret = net_slirp_init(vlan);
2635 if (!strcmp(device, "tap")) {
2637 char setup_script[1024];
2639 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
2640 fd = strtol(buf, NULL, 0);
2642 if (net_tap_fd_init(vlan, fd))
2645 get_param_value(ifname, sizeof(ifname), "ifname", p);
2646 if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
2647 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
2649 ret = net_tap_init(vlan, ifname, setup_script);
2652 if (!strcmp(device, "socket")) {
2653 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
2655 fd = strtol(buf, NULL, 0);
2657 if (net_socket_fd_init(vlan, fd, 1))
2659 } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
2660 ret = net_socket_listen_init(vlan, buf);
2661 } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
2662 ret = net_socket_connect_init(vlan, buf);
2663 } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
2664 ret = net_socket_mcast_init(vlan, buf);
2666 fprintf(stderr, "Unknown socket options: %s\n", p);
2672 fprintf(stderr, "Unknown network device: %s\n", device);
2676 fprintf(stderr, "Could not initialize device '%s'\n", device);
2682 void do_info_network(void)
2685 VLANClientState *vc;
2687 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
2688 term_printf("VLAN %d devices:\n", vlan->id);
2689 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
2690 term_printf(" %s\n", vc->info_str);
2694 /***********************************************************/
2697 static int usb_device_add(const char *devname)
2705 for(i = 0;i < MAX_VM_USB_PORTS; i++) {
2706 if (!vm_usb_ports[i]->dev)
2709 if (i == MAX_VM_USB_PORTS)
2712 if (strstart(devname, "host:", &p)) {
2713 dev = usb_host_device_open(p);
2716 } else if (!strcmp(devname, "mouse")) {
2717 dev = usb_mouse_init();
2723 usb_attach(vm_usb_ports[i], dev);
2727 static int usb_device_del(const char *devname)
2730 int bus_num, addr, i;
2736 p = strchr(devname, '.');
2739 bus_num = strtoul(devname, NULL, 0);
2740 addr = strtoul(p + 1, NULL, 0);
2743 for(i = 0;i < MAX_VM_USB_PORTS; i++) {
2744 dev = vm_usb_ports[i]->dev;
2745 if (dev && dev->addr == addr)
2748 if (i == MAX_VM_USB_PORTS)
2750 usb_attach(vm_usb_ports[i], NULL);
2754 void do_usb_add(const char *devname)
2757 ret = usb_device_add(devname);
2759 term_printf("Could not add USB device '%s'\n", devname);
2762 void do_usb_del(const char *devname)
2765 ret = usb_device_del(devname);
2767 term_printf("Could not remove USB device '%s'\n", devname);
2774 const char *speed_str;
2777 term_printf("USB support not enabled\n");
2781 for(i = 0; i < MAX_VM_USB_PORTS; i++) {
2782 dev = vm_usb_ports[i]->dev;
2784 term_printf("Hub port %d:\n", i);
2785 switch(dev->speed) {
2789 case USB_SPEED_FULL:
2792 case USB_SPEED_HIGH:
2799 term_printf(" Device %d.%d, speed %s Mb/s\n",
2800 0, dev->addr, speed_str);
2805 /***********************************************************/
2808 static char *pid_filename;
2810 /* Remove PID file. Called on normal exit */
2812 static void remove_pidfile(void)
2814 unlink (pid_filename);
2817 static void create_pidfile(const char *filename)
2819 struct stat pidstat;
2822 /* Try to write our PID to the named file */
2823 if (stat(filename, &pidstat) < 0) {
2824 if (errno == ENOENT) {
2825 if ((f = fopen (filename, "w")) == NULL) {
2826 perror("Opening pidfile");
2829 fprintf(f, "%d\n", getpid());
2831 pid_filename = qemu_strdup(filename);
2832 if (!pid_filename) {
2833 fprintf(stderr, "Could not save PID filename");
2836 atexit(remove_pidfile);
2839 fprintf(stderr, "%s already exists. Remove it and try again.\n",
2845 /***********************************************************/
2848 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
2852 static void dumb_resize(DisplayState *ds, int w, int h)
2856 static void dumb_refresh(DisplayState *ds)
2858 vga_update_display();
2861 void dumb_display_init(DisplayState *ds)
2866 ds->dpy_update = dumb_update;
2867 ds->dpy_resize = dumb_resize;
2868 ds->dpy_refresh = dumb_refresh;
2871 #if !defined(CONFIG_SOFTMMU)
2872 /***********************************************************/
2873 /* cpu signal handler */
2874 static void host_segv_handler(int host_signum, siginfo_t *info,
2877 if (cpu_signal_handler(host_signum, info, puc))
2879 if (stdio_nb_clients > 0)
2885 /***********************************************************/
2888 #define MAX_IO_HANDLERS 64
2890 typedef struct IOHandlerRecord {
2892 IOCanRWHandler *fd_read_poll;
2894 IOHandler *fd_write;
2896 /* temporary data */
2898 struct IOHandlerRecord *next;
2901 static IOHandlerRecord *first_io_handler;
2903 /* XXX: fd_read_poll should be suppressed, but an API change is
2904 necessary in the character devices to suppress fd_can_read(). */
2905 int qemu_set_fd_handler2(int fd,
2906 IOCanRWHandler *fd_read_poll,
2908 IOHandler *fd_write,
2911 IOHandlerRecord **pioh, *ioh;
2913 if (!fd_read && !fd_write) {
2914 pioh = &first_io_handler;
2919 if (ioh->fd == fd) {
2926 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2930 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
2933 ioh->next = first_io_handler;
2934 first_io_handler = ioh;
2937 ioh->fd_read_poll = fd_read_poll;
2938 ioh->fd_read = fd_read;
2939 ioh->fd_write = fd_write;
2940 ioh->opaque = opaque;
2945 int qemu_set_fd_handler(int fd,
2947 IOHandler *fd_write,
2950 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
2953 /***********************************************************/
2954 /* savevm/loadvm support */
2956 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
2958 fwrite(buf, 1, size, f);
2961 void qemu_put_byte(QEMUFile *f, int v)
2966 void qemu_put_be16(QEMUFile *f, unsigned int v)
2968 qemu_put_byte(f, v >> 8);
2969 qemu_put_byte(f, v);
2972 void qemu_put_be32(QEMUFile *f, unsigned int v)
2974 qemu_put_byte(f, v >> 24);
2975 qemu_put_byte(f, v >> 16);
2976 qemu_put_byte(f, v >> 8);
2977 qemu_put_byte(f, v);
2980 void qemu_put_be64(QEMUFile *f, uint64_t v)
2982 qemu_put_be32(f, v >> 32);
2983 qemu_put_be32(f, v);
2986 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size)
2988 return fread(buf, 1, size, f);
2991 int qemu_get_byte(QEMUFile *f)
3001 unsigned int qemu_get_be16(QEMUFile *f)
3004 v = qemu_get_byte(f) << 8;
3005 v |= qemu_get_byte(f);
3009 unsigned int qemu_get_be32(QEMUFile *f)
3012 v = qemu_get_byte(f) << 24;
3013 v |= qemu_get_byte(f) << 16;
3014 v |= qemu_get_byte(f) << 8;
3015 v |= qemu_get_byte(f);
3019 uint64_t qemu_get_be64(QEMUFile *f)
3022 v = (uint64_t)qemu_get_be32(f) << 32;
3023 v |= qemu_get_be32(f);
3027 int64_t qemu_ftell(QEMUFile *f)
3032 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
3034 if (fseek(f, pos, whence) < 0)
3039 typedef struct SaveStateEntry {
3043 SaveStateHandler *save_state;
3044 LoadStateHandler *load_state;
3046 struct SaveStateEntry *next;
3049 static SaveStateEntry *first_se;
3051 int register_savevm(const char *idstr,
3054 SaveStateHandler *save_state,
3055 LoadStateHandler *load_state,
3058 SaveStateEntry *se, **pse;
3060 se = qemu_malloc(sizeof(SaveStateEntry));
3063 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
3064 se->instance_id = instance_id;
3065 se->version_id = version_id;
3066 se->save_state = save_state;
3067 se->load_state = load_state;
3068 se->opaque = opaque;
3071 /* add at the end of list */
3073 while (*pse != NULL)
3074 pse = &(*pse)->next;
3079 #define QEMU_VM_FILE_MAGIC 0x5145564d
3080 #define QEMU_VM_FILE_VERSION 0x00000001
3082 int qemu_savevm(const char *filename)
3086 int len, len_pos, cur_pos, saved_vm_running, ret;
3088 saved_vm_running = vm_running;
3091 f = fopen(filename, "wb");
3097 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
3098 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
3100 for(se = first_se; se != NULL; se = se->next) {
3102 len = strlen(se->idstr);
3103 qemu_put_byte(f, len);
3104 qemu_put_buffer(f, se->idstr, len);
3106 qemu_put_be32(f, se->instance_id);
3107 qemu_put_be32(f, se->version_id);
3109 /* record size: filled later */
3111 qemu_put_be32(f, 0);
3113 se->save_state(f, se->opaque);
3115 /* fill record size */
3117 len = ftell(f) - len_pos - 4;
3118 fseek(f, len_pos, SEEK_SET);
3119 qemu_put_be32(f, len);
3120 fseek(f, cur_pos, SEEK_SET);
3126 if (saved_vm_running)
3131 static SaveStateEntry *find_se(const char *idstr, int instance_id)
3135 for(se = first_se; se != NULL; se = se->next) {
3136 if (!strcmp(se->idstr, idstr) &&
3137 instance_id == se->instance_id)
3143 int qemu_loadvm(const char *filename)
3147 int len, cur_pos, ret, instance_id, record_len, version_id;
3148 int saved_vm_running;
3152 saved_vm_running = vm_running;
3155 f = fopen(filename, "rb");
3161 v = qemu_get_be32(f);
3162 if (v != QEMU_VM_FILE_MAGIC)
3164 v = qemu_get_be32(f);
3165 if (v != QEMU_VM_FILE_VERSION) {
3172 len = qemu_get_byte(f);
3175 qemu_get_buffer(f, idstr, len);
3177 instance_id = qemu_get_be32(f);
3178 version_id = qemu_get_be32(f);
3179 record_len = qemu_get_be32(f);
3181 printf("idstr=%s instance=0x%x version=%d len=%d\n",
3182 idstr, instance_id, version_id, record_len);
3185 se = find_se(idstr, instance_id);
3187 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
3188 instance_id, idstr);
3190 ret = se->load_state(f, se->opaque, version_id);
3192 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
3193 instance_id, idstr);
3196 /* always seek to exact end of record */
3197 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
3202 if (saved_vm_running)
3207 /***********************************************************/
3208 /* cpu save/restore */
3210 #if defined(TARGET_I386)
3212 static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
3214 qemu_put_be32(f, dt->selector);
3215 qemu_put_betl(f, dt->base);
3216 qemu_put_be32(f, dt->limit);
3217 qemu_put_be32(f, dt->flags);
3220 static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
3222 dt->selector = qemu_get_be32(f);
3223 dt->base = qemu_get_betl(f);
3224 dt->limit = qemu_get_be32(f);
3225 dt->flags = qemu_get_be32(f);
3228 void cpu_save(QEMUFile *f, void *opaque)
3230 CPUState *env = opaque;
3231 uint16_t fptag, fpus, fpuc, fpregs_format;
3235 for(i = 0; i < CPU_NB_REGS; i++)
3236 qemu_put_betls(f, &env->regs[i]);
3237 qemu_put_betls(f, &env->eip);
3238 qemu_put_betls(f, &env->eflags);
3239 hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
3240 qemu_put_be32s(f, &hflags);
3244 fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
3246 for(i = 0; i < 8; i++) {
3247 fptag |= ((!env->fptags[i]) << i);
3250 qemu_put_be16s(f, &fpuc);
3251 qemu_put_be16s(f, &fpus);
3252 qemu_put_be16s(f, &fptag);
3254 #ifdef USE_X86LDOUBLE
3259 qemu_put_be16s(f, &fpregs_format);
3261 for(i = 0; i < 8; i++) {
3262 #ifdef USE_X86LDOUBLE
3266 /* we save the real CPU data (in case of MMX usage only 'mant'
3267 contains the MMX register */
3268 cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
3269 qemu_put_be64(f, mant);
3270 qemu_put_be16(f, exp);
3273 /* if we use doubles for float emulation, we save the doubles to
3274 avoid losing information in case of MMX usage. It can give
3275 problems if the image is restored on a CPU where long
3276 doubles are used instead. */
3277 qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
3281 for(i = 0; i < 6; i++)
3282 cpu_put_seg(f, &env->segs[i]);
3283 cpu_put_seg(f, &env->ldt);
3284 cpu_put_seg(f, &env->tr);
3285 cpu_put_seg(f, &env->gdt);
3286 cpu_put_seg(f, &env->idt);
3288 qemu_put_be32s(f, &env->sysenter_cs);
3289 qemu_put_be32s(f, &env->sysenter_esp);
3290 qemu_put_be32s(f, &env->sysenter_eip);
3292 qemu_put_betls(f, &env->cr[0]);
3293 qemu_put_betls(f, &env->cr[2]);
3294 qemu_put_betls(f, &env->cr[3]);
3295 qemu_put_betls(f, &env->cr[4]);
3297 for(i = 0; i < 8; i++)
3298 qemu_put_betls(f, &env->dr[i]);
3301 qemu_put_be32s(f, &env->a20_mask);
3304 qemu_put_be32s(f, &env->mxcsr);
3305 for(i = 0; i < CPU_NB_REGS; i++) {
3306 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
3307 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
3310 #ifdef TARGET_X86_64
3311 qemu_put_be64s(f, &env->efer);
3312 qemu_put_be64s(f, &env->star);
3313 qemu_put_be64s(f, &env->lstar);
3314 qemu_put_be64s(f, &env->cstar);
3315 qemu_put_be64s(f, &env->fmask);
3316 qemu_put_be64s(f, &env->kernelgsbase);
3320 #ifdef USE_X86LDOUBLE
3321 /* XXX: add that in a FPU generic layer */
3322 union x86_longdouble {
3327 #define MANTD1(fp) (fp & ((1LL << 52) - 1))
3328 #define EXPBIAS1 1023
3329 #define EXPD1(fp) ((fp >> 52) & 0x7FF)
3330 #define SIGND1(fp) ((fp >> 32) & 0x80000000)
3332 static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
3336 p->mant = (MANTD1(temp) << 11) | (1LL << 63);
3337 /* exponent + sign */
3338 e = EXPD1(temp) - EXPBIAS1 + 16383;
3339 e |= SIGND1(temp) >> 16;
3344 int cpu_load(QEMUFile *f, void *opaque, int version_id)
3346 CPUState *env = opaque;
3349 uint16_t fpus, fpuc, fptag, fpregs_format;
3351 if (version_id != 3)
3353 for(i = 0; i < CPU_NB_REGS; i++)
3354 qemu_get_betls(f, &env->regs[i]);
3355 qemu_get_betls(f, &env->eip);
3356 qemu_get_betls(f, &env->eflags);
3357 qemu_get_be32s(f, &hflags);
3359 qemu_get_be16s(f, &fpuc);
3360 qemu_get_be16s(f, &fpus);
3361 qemu_get_be16s(f, &fptag);
3362 qemu_get_be16s(f, &fpregs_format);
3364 /* NOTE: we cannot always restore the FPU state if the image come
3365 from a host with a different 'USE_X86LDOUBLE' define. We guess
3366 if we are in an MMX state to restore correctly in that case. */
3367 guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
3368 for(i = 0; i < 8; i++) {
3372 switch(fpregs_format) {
3374 mant = qemu_get_be64(f);
3375 exp = qemu_get_be16(f);
3376 #ifdef USE_X86LDOUBLE
3377 env->fpregs[i].d = cpu_set_fp80(mant, exp);
3379 /* difficult case */
3381 env->fpregs[i].mmx.MMX_Q(0) = mant;
3383 env->fpregs[i].d = cpu_set_fp80(mant, exp);
3387 mant = qemu_get_be64(f);
3388 #ifdef USE_X86LDOUBLE
3390 union x86_longdouble *p;
3391 /* difficult case */
3392 p = (void *)&env->fpregs[i];
3397 fp64_to_fp80(p, mant);
3401 env->fpregs[i].mmx.MMX_Q(0) = mant;
3410 /* XXX: restore FPU round state */
3411 env->fpstt = (fpus >> 11) & 7;
3412 env->fpus = fpus & ~0x3800;
3414 for(i = 0; i < 8; i++) {
3415 env->fptags[i] = (fptag >> i) & 1;
3418 for(i = 0; i < 6; i++)
3419 cpu_get_seg(f, &env->segs[i]);
3420 cpu_get_seg(f, &env->ldt);
3421 cpu_get_seg(f, &env->tr);
3422 cpu_get_seg(f, &env->gdt);
3423 cpu_get_seg(f, &env->idt);
3425 qemu_get_be32s(f, &env->sysenter_cs);
3426 qemu_get_be32s(f, &env->sysenter_esp);
3427 qemu_get_be32s(f, &env->sysenter_eip);
3429 qemu_get_betls(f, &env->cr[0]);
3430 qemu_get_betls(f, &env->cr[2]);
3431 qemu_get_betls(f, &env->cr[3]);
3432 qemu_get_betls(f, &env->cr[4]);
3434 for(i = 0; i < 8; i++)
3435 qemu_get_betls(f, &env->dr[i]);
3438 qemu_get_be32s(f, &env->a20_mask);
3440 qemu_get_be32s(f, &env->mxcsr);
3441 for(i = 0; i < CPU_NB_REGS; i++) {
3442 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
3443 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
3446 #ifdef TARGET_X86_64
3447 qemu_get_be64s(f, &env->efer);
3448 qemu_get_be64s(f, &env->star);
3449 qemu_get_be64s(f, &env->lstar);
3450 qemu_get_be64s(f, &env->cstar);
3451 qemu_get_be64s(f, &env->fmask);
3452 qemu_get_be64s(f, &env->kernelgsbase);
3455 /* XXX: compute hflags from scratch, except for CPL and IIF */
3456 env->hflags = hflags;
3461 #elif defined(TARGET_PPC)
3462 void cpu_save(QEMUFile *f, void *opaque)
3466 int cpu_load(QEMUFile *f, void *opaque, int version_id)
3471 #elif defined(TARGET_MIPS)
3472 void cpu_save(QEMUFile *f, void *opaque)
3476 int cpu_load(QEMUFile *f, void *opaque, int version_id)
3481 #elif defined(TARGET_SPARC)
3482 void cpu_save(QEMUFile *f, void *opaque)
3484 CPUState *env = opaque;
3488 for(i = 0; i < 8; i++)
3489 qemu_put_betls(f, &env->gregs[i]);
3490 for(i = 0; i < NWINDOWS * 16; i++)
3491 qemu_put_betls(f, &env->regbase[i]);
3494 for(i = 0; i < TARGET_FPREGS; i++) {
3500 qemu_put_betl(f, u.i);
3503 qemu_put_betls(f, &env->pc);
3504 qemu_put_betls(f, &env->npc);
3505 qemu_put_betls(f, &env->y);
3507 qemu_put_be32(f, tmp);
3508 qemu_put_betls(f, &env->fsr);
3509 qemu_put_betls(f, &env->tbr);
3510 #ifndef TARGET_SPARC64
3511 qemu_put_be32s(f, &env->wim);
3513 for(i = 0; i < 16; i++)
3514 qemu_put_be32s(f, &env->mmuregs[i]);
3518 int cpu_load(QEMUFile *f, void *opaque, int version_id)
3520 CPUState *env = opaque;
3524 for(i = 0; i < 8; i++)
3525 qemu_get_betls(f, &env->gregs[i]);
3526 for(i = 0; i < NWINDOWS * 16; i++)
3527 qemu_get_betls(f, &env->regbase[i]);
3530 for(i = 0; i < TARGET_FPREGS; i++) {
3535 u.i = qemu_get_betl(f);
3539 qemu_get_betls(f, &env->pc);
3540 qemu_get_betls(f, &env->npc);
3541 qemu_get_betls(f, &env->y);
3542 tmp = qemu_get_be32(f);
3543 env->cwp = 0; /* needed to ensure that the wrapping registers are
3544 correctly updated */
3546 qemu_get_betls(f, &env->fsr);
3547 qemu_get_betls(f, &env->tbr);
3548 #ifndef TARGET_SPARC64
3549 qemu_get_be32s(f, &env->wim);
3551 for(i = 0; i < 16; i++)
3552 qemu_get_be32s(f, &env->mmuregs[i]);
3558 #elif defined(TARGET_ARM)
3560 /* ??? Need to implement these. */
3561 void cpu_save(QEMUFile *f, void *opaque)
3565 int cpu_load(QEMUFile *f, void *opaque, int version_id)
3572 #warning No CPU save/restore functions
3576 /***********************************************************/
3577 /* ram save/restore */
3579 /* we just avoid storing empty pages */
3580 static void ram_put_page(QEMUFile *f, const uint8_t *buf, int len)
3585 for(i = 1; i < len; i++) {
3589 qemu_put_byte(f, 1);
3590 qemu_put_byte(f, v);
3593 qemu_put_byte(f, 0);
3594 qemu_put_buffer(f, buf, len);
3597 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
3601 v = qemu_get_byte(f);
3604 if (qemu_get_buffer(f, buf, len) != len)
3608 v = qemu_get_byte(f);
3609 memset(buf, v, len);
3617 static void ram_save(QEMUFile *f, void *opaque)
3620 qemu_put_be32(f, phys_ram_size);
3621 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
3622 ram_put_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
3626 static int ram_load(QEMUFile *f, void *opaque, int version_id)
3630 if (version_id != 1)
3632 if (qemu_get_be32(f) != phys_ram_size)
3634 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
3635 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
3642 /***********************************************************/
3643 /* machine registration */
3645 QEMUMachine *first_machine = NULL;
3647 int qemu_register_machine(QEMUMachine *m)
3650 pm = &first_machine;
3658 QEMUMachine *find_machine(const char *name)
3662 for(m = first_machine; m != NULL; m = m->next) {
3663 if (!strcmp(m->name, name))
3669 /***********************************************************/
3670 /* main execution loop */
3672 void gui_update(void *opaque)
3674 display_state.dpy_refresh(&display_state);
3675 qemu_mod_timer(gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
3678 struct vm_change_state_entry {
3679 VMChangeStateHandler *cb;
3681 LIST_ENTRY (vm_change_state_entry) entries;
3684 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3686 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3689 VMChangeStateEntry *e;
3691 e = qemu_mallocz(sizeof (*e));
3697 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3701 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3703 LIST_REMOVE (e, entries);
3707 static void vm_state_notify(int running)
3709 VMChangeStateEntry *e;
3711 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3712 e->cb(e->opaque, running);
3716 /* XXX: support several handlers */
3717 static VMStopHandler *vm_stop_cb;
3718 static void *vm_stop_opaque;
3720 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
3723 vm_stop_opaque = opaque;
3727 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
3741 void vm_stop(int reason)
3744 cpu_disable_ticks();
3748 vm_stop_cb(vm_stop_opaque, reason);
3755 /* reset/shutdown handler */
3757 typedef struct QEMUResetEntry {
3758 QEMUResetHandler *func;
3760 struct QEMUResetEntry *next;
3763 static QEMUResetEntry *first_reset_entry;
3764 static int reset_requested;
3765 static int shutdown_requested;
3766 static int powerdown_requested;
3768 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
3770 QEMUResetEntry **pre, *re;
3772 pre = &first_reset_entry;
3773 while (*pre != NULL)
3774 pre = &(*pre)->next;
3775 re = qemu_mallocz(sizeof(QEMUResetEntry));
3777 re->opaque = opaque;
3782 void qemu_system_reset(void)
3786 /* reset all devices */
3787 for(re = first_reset_entry; re != NULL; re = re->next) {
3788 re->func(re->opaque);
3792 void qemu_system_reset_request(void)
3794 reset_requested = 1;
3796 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
3799 void qemu_system_shutdown_request(void)
3801 shutdown_requested = 1;
3803 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
3806 void qemu_system_powerdown_request(void)
3808 powerdown_requested = 1;
3810 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
3813 void main_loop_wait(int timeout)
3816 struct pollfd ufds[MAX_IO_HANDLERS + 1], *pf;
3817 IOHandlerRecord *ioh, *ioh_next;
3825 /* poll any events */
3826 /* XXX: separate device handlers from system ones */
3828 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3832 (!ioh->fd_read_poll ||
3833 ioh->fd_read_poll(ioh->opaque) != 0)) {
3834 pf->events |= POLLIN;
3836 if (ioh->fd_write) {
3837 pf->events |= POLLOUT;
3843 ret = poll(ufds, pf - ufds, timeout);
3845 /* XXX: better handling of removal */
3846 for(ioh = first_io_handler; ioh != NULL; ioh = ioh_next) {
3847 ioh_next = ioh->next;
3849 if (pf->revents & POLLIN) {
3850 ioh->fd_read(ioh->opaque);
3852 if (pf->revents & POLLOUT) {
3853 ioh->fd_write(ioh->opaque);
3857 #endif /* !defined(_WIN32) */
3858 #if defined(CONFIG_SLIRP)
3859 /* XXX: merge with poll() */
3861 fd_set rfds, wfds, xfds;
3869 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
3872 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
3874 slirp_select_poll(&rfds, &wfds, &xfds);
3880 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
3881 qemu_get_clock(vm_clock));
3882 /* run dma transfers, if any */
3886 /* real time timers */
3887 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
3888 qemu_get_clock(rt_clock));
3891 static CPUState *cur_cpu;
3898 cur_cpu = first_cpu;
3905 env = env->next_cpu;
3908 ret = cpu_exec(env);
3909 if (ret != EXCP_HALTED)
3911 /* all CPUs are halted ? */
3912 if (env == cur_cpu) {
3919 if (shutdown_requested) {
3920 ret = EXCP_INTERRUPT;
3923 if (reset_requested) {
3924 reset_requested = 0;
3925 qemu_system_reset();
3926 ret = EXCP_INTERRUPT;
3928 if (powerdown_requested) {
3929 powerdown_requested = 0;
3930 qemu_system_powerdown();
3931 ret = EXCP_INTERRUPT;
3933 if (ret == EXCP_DEBUG) {
3934 vm_stop(EXCP_DEBUG);
3936 /* if hlt instruction, we wait until the next IRQ */
3937 /* XXX: use timeout computed from timers */
3938 if (ret == EXCP_HLT)
3945 main_loop_wait(timeout);
3947 cpu_disable_ticks();
3953 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2005 Fabrice Bellard\n"
3954 "usage: %s [options] [disk_image]\n"
3956 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
3958 "Standard options:\n"
3959 "-M machine select emulated machine (-M ? for list)\n"
3960 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
3961 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
3962 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
3963 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
3964 "-boot [a|c|d] boot on floppy (a), hard disk (c) or CD-ROM (d)\n"
3965 "-snapshot write to temporary files instead of disk image files\n"
3966 "-m megs set virtual RAM size to megs MB [default=%d]\n"
3967 "-smp n set the number of CPUs to 'n' [default=1]\n"
3968 "-nographic disable graphical output and redirect serial I/Os to console\n"
3970 "-k language use keyboard layout (for example \"fr\" for French)\n"
3973 "-audio-help print list of audio drivers and their options\n"
3974 "-soundhw c1,... enable audio support\n"
3975 " and only specified sound cards (comma separated list)\n"
3976 " use -soundhw ? to get the list of supported cards\n"
3977 " use -soundhw all to enable all of them\n"
3979 "-localtime set the real time clock to local time [default=utc]\n"
3980 "-full-screen start in full screen\n"
3982 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
3984 "-usb enable the USB driver (will be the default soon)\n"
3985 "-usbdevice name add the host or guest USB device 'name'\n"
3986 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
3987 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
3990 "Network options:\n"
3991 "-net nic[,vlan=n][,macaddr=addr]\n"
3992 " create a new Network Interface Card and connect it to VLAN 'n'\n"
3994 "-net user[,vlan=n]\n"
3995 " connect the user mode network stack to VLAN 'n'\n"
3998 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file]\n"
3999 " connect the host TAP network interface to VLAN 'n' and use\n"
4000 " the network script 'file' (default=%s);\n"
4001 " use 'fd=h' to connect to an already opened TAP interface\n"
4002 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
4003 " connect the vlan 'n' to another VLAN using a socket connection\n"
4004 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
4005 " connect the vlan 'n' to multicast maddr and port\n"
4007 "-net none use it alone to have zero network devices; if no -net option\n"
4008 " is provided, the default is '-net nic -net user'\n"
4011 "-tftp prefix allow tftp access to files starting with prefix [-net user]\n"
4013 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
4015 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
4016 " redirect TCP or UDP connections from host to guest [-net user]\n"
4019 "Linux boot specific:\n"
4020 "-kernel bzImage use 'bzImage' as kernel image\n"
4021 "-append cmdline use 'cmdline' as kernel command line\n"
4022 "-initrd file use 'file' as initial ram disk\n"
4024 "Debug/Expert options:\n"
4025 "-monitor dev redirect the monitor to char device 'dev'\n"
4026 "-serial dev redirect the serial port to char device 'dev'\n"
4027 "-parallel dev redirect the parallel port to char device 'dev'\n"
4028 "-pidfile file Write PID to 'file'\n"
4029 "-S freeze CPU at startup (use 'c' to start execution)\n"
4030 "-s wait gdb connection to port %d\n"
4031 "-p port change gdb connection port\n"
4032 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
4033 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
4034 " translation (t=none or lba) (usually qemu can guess them)\n"
4035 "-L path set the directory for the BIOS and VGA BIOS\n"
4037 "-no-kqemu disable KQEMU kernel module usage\n"
4039 #ifdef USE_CODE_COPY
4040 "-no-code-copy disable code copy acceleration\n"
4043 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
4044 " (default is CL-GD5446 PCI VGA)\n"
4046 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
4048 "During emulation, the following keys are useful:\n"
4049 "ctrl-alt-f toggle full screen\n"
4050 "ctrl-alt-n switch to virtual console 'n'\n"
4051 "ctrl-alt toggle mouse and keyboard grab\n"
4053 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4055 #ifdef CONFIG_SOFTMMU
4062 DEFAULT_NETWORK_SCRIPT,
4064 DEFAULT_GDBSTUB_PORT,
4066 #ifndef CONFIG_SOFTMMU
4068 "NOTE: this version of QEMU is faster but it needs slightly patched OSes to\n"
4069 "work. Please use the 'qemu' executable to have a more accurate (but slower)\n"
4075 #define HAS_ARG 0x0001
4089 QEMU_OPTION_snapshot,
4091 QEMU_OPTION_nographic,
4093 QEMU_OPTION_audio_help,
4094 QEMU_OPTION_soundhw,
4112 QEMU_OPTION_no_code_copy,
4114 QEMU_OPTION_localtime,
4115 QEMU_OPTION_cirrusvga,
4117 QEMU_OPTION_std_vga,
4118 QEMU_OPTION_monitor,
4120 QEMU_OPTION_parallel,
4122 QEMU_OPTION_full_screen,
4123 QEMU_OPTION_pidfile,
4124 QEMU_OPTION_no_kqemu,
4125 QEMU_OPTION_win2k_hack,
4127 QEMU_OPTION_usbdevice,
4131 typedef struct QEMUOption {
4137 const QEMUOption qemu_options[] = {
4138 { "h", 0, QEMU_OPTION_h },
4140 { "M", HAS_ARG, QEMU_OPTION_M },
4141 { "fda", HAS_ARG, QEMU_OPTION_fda },
4142 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
4143 { "hda", HAS_ARG, QEMU_OPTION_hda },
4144 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
4145 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
4146 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
4147 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
4148 { "boot", HAS_ARG, QEMU_OPTION_boot },
4149 { "snapshot", 0, QEMU_OPTION_snapshot },
4150 { "m", HAS_ARG, QEMU_OPTION_m },
4151 { "nographic", 0, QEMU_OPTION_nographic },
4152 { "k", HAS_ARG, QEMU_OPTION_k },
4154 { "audio-help", 0, QEMU_OPTION_audio_help },
4155 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
4158 { "net", HAS_ARG, QEMU_OPTION_net},
4160 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
4162 { "smb", HAS_ARG, QEMU_OPTION_smb },
4164 { "redir", HAS_ARG, QEMU_OPTION_redir },
4167 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
4168 { "append", HAS_ARG, QEMU_OPTION_append },
4169 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
4171 { "S", 0, QEMU_OPTION_S },
4172 { "s", 0, QEMU_OPTION_s },
4173 { "p", HAS_ARG, QEMU_OPTION_p },
4174 { "d", HAS_ARG, QEMU_OPTION_d },
4175 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
4176 { "L", HAS_ARG, QEMU_OPTION_L },
4177 { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
4179 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
4181 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
4182 { "g", 1, QEMU_OPTION_g },
4184 { "localtime", 0, QEMU_OPTION_localtime },
4185 { "std-vga", 0, QEMU_OPTION_std_vga },
4186 { "monitor", 1, QEMU_OPTION_monitor },
4187 { "serial", 1, QEMU_OPTION_serial },
4188 { "parallel", 1, QEMU_OPTION_parallel },
4189 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
4190 { "full-screen", 0, QEMU_OPTION_full_screen },
4191 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
4192 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
4193 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
4194 { "smp", HAS_ARG, QEMU_OPTION_smp },
4196 /* temporary options */
4197 { "usb", 0, QEMU_OPTION_usb },
4198 { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
4202 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
4204 /* this stack is only used during signal handling */
4205 #define SIGNAL_STACK_SIZE 32768
4207 static uint8_t *signal_stack;
4211 /* password input */
4213 static BlockDriverState *get_bdrv(int index)
4215 BlockDriverState *bs;
4218 bs = bs_table[index];
4219 } else if (index < 6) {
4220 bs = fd_table[index - 4];
4227 static void read_passwords(void)
4229 BlockDriverState *bs;
4233 for(i = 0; i < 6; i++) {
4235 if (bs && bdrv_is_encrypted(bs)) {
4236 term_printf("%s is encrypted.\n", bdrv_get_device_name(bs));
4237 for(j = 0; j < 3; j++) {
4238 monitor_readline("Password: ",
4239 1, password, sizeof(password));
4240 if (bdrv_set_key(bs, password) == 0)
4242 term_printf("invalid password\n");
4248 /* XXX: currently we cannot use simultaneously different CPUs */
4249 void register_machines(void)
4251 #if defined(TARGET_I386)
4252 qemu_register_machine(&pc_machine);
4253 qemu_register_machine(&isapc_machine);
4254 #elif defined(TARGET_PPC)
4255 qemu_register_machine(&heathrow_machine);
4256 qemu_register_machine(&core99_machine);
4257 qemu_register_machine(&prep_machine);
4258 #elif defined(TARGET_MIPS)
4259 qemu_register_machine(&mips_machine);
4260 #elif defined(TARGET_SPARC)
4261 #ifdef TARGET_SPARC64
4262 qemu_register_machine(&sun4u_machine);
4264 qemu_register_machine(&sun4m_machine);
4266 #elif defined(TARGET_ARM)
4267 qemu_register_machine(&integratorcp_machine);
4269 #error unsupported CPU
4274 struct soundhw soundhw[] = {
4277 "Creative Sound Blaster 16",
4280 { .init_isa = SB16_init }
4287 "Yamaha YMF262 (OPL3)",
4289 "Yamaha YM3812 (OPL2)",
4293 { .init_isa = Adlib_init }
4300 "Gravis Ultrasound GF1",
4303 { .init_isa = GUS_init }
4309 "ENSONIQ AudioPCI ES1370",
4312 { .init_pci = es1370_init }
4315 { NULL, NULL, 0, 0, { NULL } }
4318 static void select_soundhw (const char *optarg)
4322 if (*optarg == '?') {
4325 printf ("Valid sound card names (comma separated):\n");
4326 for (c = soundhw; c->name; ++c) {
4327 printf ("%-11s %s\n", c->name, c->descr);
4329 printf ("\n-soundhw all will enable all of the above\n");
4330 exit (*optarg != '?');
4338 if (!strcmp (optarg, "all")) {
4339 for (c = soundhw; c->name; ++c) {
4347 e = strchr (p, ',');
4348 l = !e ? strlen (p) : (size_t) (e - p);
4350 for (c = soundhw; c->name; ++c) {
4351 if (!strncmp (c->name, p, l)) {
4360 "Unknown sound card name (too big to show)\n");
4363 fprintf (stderr, "Unknown sound card name `%.*s'\n",
4368 p += l + (e != NULL);
4372 goto show_valid_cards;
4377 #define MAX_NET_CLIENTS 32
4379 int main(int argc, char **argv)
4381 #ifdef CONFIG_GDBSTUB
4382 int use_gdbstub, gdbstub_port;
4385 int snapshot, linux_boot;
4386 const char *initrd_filename;
4387 const char *hd_filename[MAX_DISKS], *fd_filename[MAX_FD];
4388 const char *kernel_filename, *kernel_cmdline;
4389 DisplayState *ds = &display_state;
4390 int cyls, heads, secs, translation;
4391 int start_emulation = 1;
4392 char net_clients[MAX_NET_CLIENTS][256];
4395 const char *r, *optarg;
4396 CharDriverState *monitor_hd;
4397 char monitor_device[128];
4398 char serial_devices[MAX_SERIAL_PORTS][128];
4399 int serial_device_index;
4400 char parallel_devices[MAX_PARALLEL_PORTS][128];
4401 int parallel_device_index;
4402 const char *loadvm = NULL;
4403 QEMUMachine *machine;
4404 char usb_devices[MAX_VM_USB_PORTS][128];
4405 int usb_devices_index;
4407 LIST_INIT (&vm_change_state_head);
4408 #if !defined(CONFIG_SOFTMMU)
4409 /* we never want that malloc() uses mmap() */
4410 mallopt(M_MMAP_THRESHOLD, 4096 * 1024);
4412 register_machines();
4413 machine = first_machine;
4414 initrd_filename = NULL;
4415 for(i = 0; i < MAX_FD; i++)
4416 fd_filename[i] = NULL;
4417 for(i = 0; i < MAX_DISKS; i++)
4418 hd_filename[i] = NULL;
4419 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
4420 vga_ram_size = VGA_RAM_SIZE;
4421 bios_size = BIOS_SIZE;
4422 #ifdef CONFIG_GDBSTUB
4424 gdbstub_port = DEFAULT_GDBSTUB_PORT;
4428 kernel_filename = NULL;
4429 kernel_cmdline = "";
4435 cyls = heads = secs = 0;
4436 translation = BIOS_ATA_TRANSLATION_AUTO;
4437 pstrcpy(monitor_device, sizeof(monitor_device), "vc");
4439 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
4440 for(i = 1; i < MAX_SERIAL_PORTS; i++)
4441 serial_devices[i][0] = '\0';
4442 serial_device_index = 0;
4444 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
4445 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
4446 parallel_devices[i][0] = '\0';
4447 parallel_device_index = 0;
4449 usb_devices_index = 0;
4454 /* default mac address of the first network interface */
4462 hd_filename[0] = argv[optind++];
4464 const QEMUOption *popt;
4467 popt = qemu_options;
4470 fprintf(stderr, "%s: invalid option -- '%s'\n",
4474 if (!strcmp(popt->name, r + 1))
4478 if (popt->flags & HAS_ARG) {
4479 if (optind >= argc) {
4480 fprintf(stderr, "%s: option '%s' requires an argument\n",
4484 optarg = argv[optind++];
4489 switch(popt->index) {
4491 machine = find_machine(optarg);
4494 printf("Supported machines are:\n");
4495 for(m = first_machine; m != NULL; m = m->next) {
4496 printf("%-10s %s%s\n",
4498 m == first_machine ? " (default)" : "");
4503 case QEMU_OPTION_initrd:
4504 initrd_filename = optarg;
4506 case QEMU_OPTION_hda:
4507 case QEMU_OPTION_hdb:
4508 case QEMU_OPTION_hdc:
4509 case QEMU_OPTION_hdd:
4512 hd_index = popt->index - QEMU_OPTION_hda;
4513 hd_filename[hd_index] = optarg;
4514 if (hd_index == cdrom_index)
4518 case QEMU_OPTION_snapshot:
4521 case QEMU_OPTION_hdachs:
4525 cyls = strtol(p, (char **)&p, 0);
4526 if (cyls < 1 || cyls > 16383)
4531 heads = strtol(p, (char **)&p, 0);
4532 if (heads < 1 || heads > 16)
4537 secs = strtol(p, (char **)&p, 0);
4538 if (secs < 1 || secs > 63)
4542 if (!strcmp(p, "none"))
4543 translation = BIOS_ATA_TRANSLATION_NONE;
4544 else if (!strcmp(p, "lba"))
4545 translation = BIOS_ATA_TRANSLATION_LBA;
4546 else if (!strcmp(p, "auto"))
4547 translation = BIOS_ATA_TRANSLATION_AUTO;
4550 } else if (*p != '\0') {
4552 fprintf(stderr, "qemu: invalid physical CHS format\n");
4557 case QEMU_OPTION_nographic:
4558 pstrcpy(monitor_device, sizeof(monitor_device), "stdio");
4559 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "stdio");
4562 case QEMU_OPTION_kernel:
4563 kernel_filename = optarg;
4565 case QEMU_OPTION_append:
4566 kernel_cmdline = optarg;
4568 case QEMU_OPTION_cdrom:
4569 if (cdrom_index >= 0) {
4570 hd_filename[cdrom_index] = optarg;
4573 case QEMU_OPTION_boot:
4574 boot_device = optarg[0];
4575 if (boot_device != 'a' &&
4578 boot_device != 'n' &&
4580 boot_device != 'c' && boot_device != 'd') {
4581 fprintf(stderr, "qemu: invalid boot device '%c'\n", boot_device);
4585 case QEMU_OPTION_fda:
4586 fd_filename[0] = optarg;
4588 case QEMU_OPTION_fdb:
4589 fd_filename[1] = optarg;
4591 case QEMU_OPTION_no_code_copy:
4592 code_copy_enabled = 0;
4594 case QEMU_OPTION_net:
4595 if (nb_net_clients >= MAX_NET_CLIENTS) {
4596 fprintf(stderr, "qemu: too many network clients\n");
4599 pstrcpy(net_clients[nb_net_clients],
4600 sizeof(net_clients[0]),
4605 case QEMU_OPTION_tftp:
4606 tftp_prefix = optarg;
4609 case QEMU_OPTION_smb:
4610 net_slirp_smb(optarg);
4613 case QEMU_OPTION_redir:
4614 net_slirp_redir(optarg);
4618 case QEMU_OPTION_audio_help:
4622 case QEMU_OPTION_soundhw:
4623 select_soundhw (optarg);
4630 ram_size = atoi(optarg) * 1024 * 1024;
4633 if (ram_size > PHYS_RAM_MAX_SIZE) {
4634 fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
4635 PHYS_RAM_MAX_SIZE / (1024 * 1024));
4644 mask = cpu_str_to_log_mask(optarg);
4646 printf("Log items (comma separated):\n");
4647 for(item = cpu_log_items; item->mask != 0; item++) {
4648 printf("%-10s %s\n", item->name, item->help);
4655 #ifdef CONFIG_GDBSTUB
4660 gdbstub_port = atoi(optarg);
4667 start_emulation = 0;
4670 keyboard_layout = optarg;
4672 case QEMU_OPTION_localtime:
4675 case QEMU_OPTION_cirrusvga:
4676 cirrus_vga_enabled = 1;
4678 case QEMU_OPTION_std_vga:
4679 cirrus_vga_enabled = 0;
4686 w = strtol(p, (char **)&p, 10);
4689 fprintf(stderr, "qemu: invalid resolution or depth\n");
4695 h = strtol(p, (char **)&p, 10);
4700 depth = strtol(p, (char **)&p, 10);
4701 if (depth != 8 && depth != 15 && depth != 16 &&
4702 depth != 24 && depth != 32)
4704 } else if (*p == '\0') {
4705 depth = graphic_depth;
4712 graphic_depth = depth;
4715 case QEMU_OPTION_monitor:
4716 pstrcpy(monitor_device, sizeof(monitor_device), optarg);
4718 case QEMU_OPTION_serial:
4719 if (serial_device_index >= MAX_SERIAL_PORTS) {
4720 fprintf(stderr, "qemu: too many serial ports\n");
4723 pstrcpy(serial_devices[serial_device_index],
4724 sizeof(serial_devices[0]), optarg);
4725 serial_device_index++;
4727 case QEMU_OPTION_parallel:
4728 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
4729 fprintf(stderr, "qemu: too many parallel ports\n");
4732 pstrcpy(parallel_devices[parallel_device_index],
4733 sizeof(parallel_devices[0]), optarg);
4734 parallel_device_index++;
4736 case QEMU_OPTION_loadvm:
4739 case QEMU_OPTION_full_screen:
4742 case QEMU_OPTION_pidfile:
4743 create_pidfile(optarg);
4746 case QEMU_OPTION_win2k_hack:
4747 win2k_install_hack = 1;
4751 case QEMU_OPTION_no_kqemu:
4755 case QEMU_OPTION_usb:
4758 case QEMU_OPTION_usbdevice:
4760 if (usb_devices_index >= MAX_VM_USB_PORTS) {
4761 fprintf(stderr, "Too many USB devices\n");
4764 pstrcpy(usb_devices[usb_devices_index],
4765 sizeof(usb_devices[usb_devices_index]),
4767 usb_devices_index++;
4769 case QEMU_OPTION_smp:
4770 smp_cpus = atoi(optarg);
4771 if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
4772 fprintf(stderr, "Invalid number of CPUs\n");
4780 linux_boot = (kernel_filename != NULL);
4783 hd_filename[0] == '\0' &&
4784 (cdrom_index >= 0 && hd_filename[cdrom_index] == '\0') &&
4785 fd_filename[0] == '\0')
4788 /* boot to cd by default if no hard disk */
4789 if (hd_filename[0] == '\0' && boot_device == 'c') {
4790 if (fd_filename[0] != '\0')
4796 #if !defined(CONFIG_SOFTMMU)
4797 /* must avoid mmap() usage of glibc by setting a buffer "by hand" */
4799 static uint8_t stdout_buf[4096];
4800 setvbuf(stdout, stdout_buf, _IOLBF, sizeof(stdout_buf));
4803 setvbuf(stdout, NULL, _IOLBF, 0);
4806 /* init network clients */
4807 if (nb_net_clients == 0) {
4808 /* if no clients, we use a default config */
4809 pstrcpy(net_clients[0], sizeof(net_clients[0]),
4811 pstrcpy(net_clients[1], sizeof(net_clients[0]),
4816 for(i = 0;i < nb_net_clients; i++) {
4817 if (net_client_init(net_clients[i]) < 0)
4821 /* init the memory */
4822 phys_ram_size = ram_size + vga_ram_size + bios_size;
4824 #ifdef CONFIG_SOFTMMU
4825 phys_ram_base = qemu_vmalloc(phys_ram_size);
4826 if (!phys_ram_base) {
4827 fprintf(stderr, "Could not allocate physical memory\n");
4831 /* as we must map the same page at several addresses, we must use
4836 tmpdir = getenv("QEMU_TMPDIR");
4839 snprintf(phys_ram_file, sizeof(phys_ram_file), "%s/vlXXXXXX", tmpdir);
4840 if (mkstemp(phys_ram_file) < 0) {
4841 fprintf(stderr, "Could not create temporary memory file '%s'\n",
4845 phys_ram_fd = open(phys_ram_file, O_CREAT | O_TRUNC | O_RDWR, 0600);
4846 if (phys_ram_fd < 0) {
4847 fprintf(stderr, "Could not open temporary memory file '%s'\n",
4851 ftruncate(phys_ram_fd, phys_ram_size);
4852 unlink(phys_ram_file);
4853 phys_ram_base = mmap(get_mmap_addr(phys_ram_size),
4855 PROT_WRITE | PROT_READ, MAP_SHARED | MAP_FIXED,
4857 if (phys_ram_base == MAP_FAILED) {
4858 fprintf(stderr, "Could not map physical memory\n");
4864 /* we always create the cdrom drive, even if no disk is there */
4866 if (cdrom_index >= 0) {
4867 bs_table[cdrom_index] = bdrv_new("cdrom");
4868 bdrv_set_type_hint(bs_table[cdrom_index], BDRV_TYPE_CDROM);
4871 /* open the virtual block devices */
4872 for(i = 0; i < MAX_DISKS; i++) {
4873 if (hd_filename[i]) {
4876 snprintf(buf, sizeof(buf), "hd%c", i + 'a');
4877 bs_table[i] = bdrv_new(buf);
4879 if (bdrv_open(bs_table[i], hd_filename[i], snapshot) < 0) {
4880 fprintf(stderr, "qemu: could not open hard disk image '%s'\n",
4884 if (i == 0 && cyls != 0) {
4885 bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
4886 bdrv_set_translation_hint(bs_table[i], translation);
4891 /* we always create at least one floppy disk */
4892 fd_table[0] = bdrv_new("fda");
4893 bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
4895 for(i = 0; i < MAX_FD; i++) {
4896 if (fd_filename[i]) {
4899 snprintf(buf, sizeof(buf), "fd%c", i + 'a');
4900 fd_table[i] = bdrv_new(buf);
4901 bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
4903 if (fd_filename[i] != '\0') {
4904 if (bdrv_open(fd_table[i], fd_filename[i], snapshot) < 0) {
4905 fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
4913 /* init USB devices */
4915 vm_usb_hub = usb_hub_init(vm_usb_ports, MAX_VM_USB_PORTS);
4916 for(i = 0; i < usb_devices_index; i++) {
4917 if (usb_device_add(usb_devices[i]) < 0) {
4918 fprintf(stderr, "Warning: could not add USB device %s\n",
4924 register_savevm("timer", 0, 1, timer_save, timer_load, NULL);
4925 register_savevm("ram", 0, 1, ram_save, ram_load, NULL);
4928 cpu_calibrate_ticks();
4932 dumb_display_init(ds);
4934 #if defined(CONFIG_SDL)
4935 sdl_display_init(ds, full_screen);
4936 #elif defined(CONFIG_COCOA)
4937 cocoa_display_init(ds, full_screen);
4939 dumb_display_init(ds);
4943 vga_console = graphic_console_init(ds);
4945 monitor_hd = qemu_chr_open(monitor_device);
4947 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
4950 monitor_init(monitor_hd, !nographic);
4952 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
4953 if (serial_devices[i][0] != '\0') {
4954 serial_hds[i] = qemu_chr_open(serial_devices[i]);
4955 if (!serial_hds[i]) {
4956 fprintf(stderr, "qemu: could not open serial device '%s'\n",
4960 if (!strcmp(serial_devices[i], "vc"))
4961 qemu_chr_printf(serial_hds[i], "serial%d console\n", i);
4965 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
4966 if (parallel_devices[i][0] != '\0') {
4967 parallel_hds[i] = qemu_chr_open(parallel_devices[i]);
4968 if (!parallel_hds[i]) {
4969 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
4970 parallel_devices[i]);
4973 if (!strcmp(parallel_devices[i], "vc"))
4974 qemu_chr_printf(parallel_hds[i], "parallel%d console\n", i);
4978 /* setup cpu signal handlers for MMU / self modifying code handling */
4979 #if !defined(CONFIG_SOFTMMU)
4981 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
4984 signal_stack = memalign(16, SIGNAL_STACK_SIZE);
4985 stk.ss_sp = signal_stack;
4986 stk.ss_size = SIGNAL_STACK_SIZE;
4989 if (sigaltstack(&stk, NULL) < 0) {
4990 perror("sigaltstack");
4996 struct sigaction act;
4998 sigfillset(&act.sa_mask);
4999 act.sa_flags = SA_SIGINFO;
5000 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
5001 act.sa_flags |= SA_ONSTACK;
5003 act.sa_sigaction = host_segv_handler;
5004 sigaction(SIGSEGV, &act, NULL);
5005 sigaction(SIGBUS, &act, NULL);
5006 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
5007 sigaction(SIGFPE, &act, NULL);
5014 struct sigaction act;
5015 sigfillset(&act.sa_mask);
5017 act.sa_handler = SIG_IGN;
5018 sigaction(SIGPIPE, &act, NULL);
5023 machine->init(ram_size, vga_ram_size, boot_device,
5024 ds, fd_filename, snapshot,
5025 kernel_filename, kernel_cmdline, initrd_filename);
5027 gui_timer = qemu_new_timer(rt_clock, gui_update, NULL);
5028 qemu_mod_timer(gui_timer, qemu_get_clock(rt_clock));
5030 #ifdef CONFIG_GDBSTUB
5032 if (gdbserver_start(gdbstub_port) < 0) {
5033 fprintf(stderr, "Could not open gdbserver socket on port %d\n",
5037 printf("Waiting gdb connection on port %d\n", gdbstub_port);
5042 qemu_loadvm(loadvm);
5045 /* XXX: simplify init */
5047 if (start_emulation) {