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 audio_enabled = 0;
129 int sb16_enabled = 0;
130 int adlib_enabled = 0;
132 int es1370_enabled = 0;
135 int cirrus_vga_enabled = 1;
137 int graphic_width = 1024;
138 int graphic_height = 768;
140 int graphic_width = 800;
141 int graphic_height = 600;
143 int graphic_depth = 15;
145 TextConsole *vga_console;
146 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
147 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
149 int win2k_install_hack = 0;
152 USBPort *vm_usb_ports[MAX_VM_USB_PORTS];
153 USBDevice *vm_usb_hub;
154 static VLANState *first_vlan;
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)
1394 char slave_name[1024];
1395 int master_fd, slave_fd;
1397 /* Not satisfying */
1398 if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
1401 fprintf(stderr, "char device redirected to %s\n", slave_name);
1402 return qemu_chr_open_fd(master_fd, master_fd);
1405 static void tty_serial_init(int fd, int speed,
1406 int parity, int data_bits, int stop_bits)
1412 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1413 speed, parity, data_bits, stop_bits);
1415 tcgetattr (fd, &tty);
1457 cfsetispeed(&tty, spd);
1458 cfsetospeed(&tty, spd);
1460 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1461 |INLCR|IGNCR|ICRNL|IXON);
1462 tty.c_oflag |= OPOST;
1463 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1464 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS);
1485 tty.c_cflag |= PARENB;
1488 tty.c_cflag |= PARENB | PARODD;
1492 tcsetattr (fd, TCSANOW, &tty);
1495 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1497 FDCharDriver *s = chr->opaque;
1500 case CHR_IOCTL_SERIAL_SET_PARAMS:
1502 QEMUSerialSetParams *ssp = arg;
1503 tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
1504 ssp->data_bits, ssp->stop_bits);
1507 case CHR_IOCTL_SERIAL_SET_BREAK:
1509 int enable = *(int *)arg;
1511 tcsendbreak(s->fd_in, 1);
1520 CharDriverState *qemu_chr_open_tty(const char *filename)
1522 CharDriverState *chr;
1525 fd = open(filename, O_RDWR | O_NONBLOCK);
1528 fcntl(fd, F_SETFL, O_NONBLOCK);
1529 tty_serial_init(fd, 115200, 'N', 8, 1);
1530 chr = qemu_chr_open_fd(fd, fd);
1533 chr->chr_ioctl = tty_serial_ioctl;
1537 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1539 int fd = (int)chr->opaque;
1543 case CHR_IOCTL_PP_READ_DATA:
1544 if (ioctl(fd, PPRDATA, &b) < 0)
1546 *(uint8_t *)arg = b;
1548 case CHR_IOCTL_PP_WRITE_DATA:
1549 b = *(uint8_t *)arg;
1550 if (ioctl(fd, PPWDATA, &b) < 0)
1553 case CHR_IOCTL_PP_READ_CONTROL:
1554 if (ioctl(fd, PPRCONTROL, &b) < 0)
1556 *(uint8_t *)arg = b;
1558 case CHR_IOCTL_PP_WRITE_CONTROL:
1559 b = *(uint8_t *)arg;
1560 if (ioctl(fd, PPWCONTROL, &b) < 0)
1563 case CHR_IOCTL_PP_READ_STATUS:
1564 if (ioctl(fd, PPRSTATUS, &b) < 0)
1566 *(uint8_t *)arg = b;
1574 CharDriverState *qemu_chr_open_pp(const char *filename)
1576 CharDriverState *chr;
1579 fd = open(filename, O_RDWR);
1583 if (ioctl(fd, PPCLAIM) < 0) {
1588 chr = qemu_mallocz(sizeof(CharDriverState));
1593 chr->opaque = (void *)fd;
1594 chr->chr_write = null_chr_write;
1595 chr->chr_add_read_handler = null_chr_add_read_handler;
1596 chr->chr_ioctl = pp_ioctl;
1601 CharDriverState *qemu_chr_open_pty(void)
1607 #endif /* !defined(_WIN32) */
1609 CharDriverState *qemu_chr_open(const char *filename)
1612 if (!strcmp(filename, "vc")) {
1613 return text_console_init(&display_state);
1614 } else if (!strcmp(filename, "null")) {
1615 return qemu_chr_open_null();
1616 } else if (strstart(filename, "file:", &p)) {
1617 return qemu_chr_open_file_out(p);
1618 } else if (strstart(filename, "pipe:", &p)) {
1619 return qemu_chr_open_pipe(p);
1622 if (!strcmp(filename, "pty")) {
1623 return qemu_chr_open_pty();
1624 } else if (!strcmp(filename, "stdio")) {
1625 return qemu_chr_open_stdio();
1628 #if defined(__linux__)
1629 if (strstart(filename, "/dev/parport", NULL)) {
1630 return qemu_chr_open_pp(filename);
1632 if (strstart(filename, "/dev/", NULL)) {
1633 return qemu_chr_open_tty(filename);
1641 /***********************************************************/
1642 /* network device redirectors */
1644 void hex_dump(FILE *f, const uint8_t *buf, int size)
1648 for(i=0;i<size;i+=16) {
1652 fprintf(f, "%08x ", i);
1655 fprintf(f, " %02x", buf[i+j]);
1660 for(j=0;j<len;j++) {
1662 if (c < ' ' || c > '~')
1664 fprintf(f, "%c", c);
1670 static int parse_macaddr(uint8_t *macaddr, const char *p)
1673 for(i = 0; i < 6; i++) {
1674 macaddr[i] = strtol(p, (char **)&p, 16);
1687 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
1692 p1 = strchr(p, sep);
1698 if (len > buf_size - 1)
1700 memcpy(buf, p, len);
1707 int parse_host_port(struct sockaddr_in *saddr, const char *str)
1715 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
1717 saddr->sin_family = AF_INET;
1718 if (buf[0] == '\0') {
1719 saddr->sin_addr.s_addr = 0;
1721 if (isdigit(buf[0])) {
1722 if (!inet_aton(buf, &saddr->sin_addr))
1728 if ((he = gethostbyname(buf)) == NULL)
1730 saddr->sin_addr = *(struct in_addr *)he->h_addr;
1734 port = strtol(p, (char **)&r, 0);
1737 saddr->sin_port = htons(port);
1741 /* find or alloc a new VLAN */
1742 VLANState *qemu_find_vlan(int id)
1744 VLANState **pvlan, *vlan;
1745 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
1749 vlan = qemu_mallocz(sizeof(VLANState));
1754 pvlan = &first_vlan;
1755 while (*pvlan != NULL)
1756 pvlan = &(*pvlan)->next;
1761 VLANClientState *qemu_new_vlan_client(VLANState *vlan,
1762 IOReadHandler *fd_read, void *opaque)
1764 VLANClientState *vc, **pvc;
1765 vc = qemu_mallocz(sizeof(VLANClientState));
1768 vc->fd_read = fd_read;
1769 vc->opaque = opaque;
1773 pvc = &vlan->first_client;
1774 while (*pvc != NULL)
1775 pvc = &(*pvc)->next;
1780 void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
1782 VLANState *vlan = vc1->vlan;
1783 VLANClientState *vc;
1786 printf("vlan %d send:\n", vlan->id);
1787 hex_dump(stdout, buf, size);
1789 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
1791 vc->fd_read(vc->opaque, buf, size);
1796 #if defined(CONFIG_SLIRP)
1798 /* slirp network adapter */
1800 static int slirp_inited;
1801 static VLANClientState *slirp_vc;
1803 int slirp_can_output(void)
1808 void slirp_output(const uint8_t *pkt, int pkt_len)
1811 printf("slirp output:\n");
1812 hex_dump(stdout, pkt, pkt_len);
1814 qemu_send_packet(slirp_vc, pkt, pkt_len);
1817 static void slirp_receive(void *opaque, const uint8_t *buf, int size)
1820 printf("slirp input:\n");
1821 hex_dump(stdout, buf, size);
1823 slirp_input(buf, size);
1826 static int net_slirp_init(VLANState *vlan)
1828 if (!slirp_inited) {
1832 slirp_vc = qemu_new_vlan_client(vlan,
1833 slirp_receive, NULL);
1834 snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
1838 static void net_slirp_redir(const char *redir_str)
1843 struct in_addr guest_addr;
1844 int host_port, guest_port;
1846 if (!slirp_inited) {
1852 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
1854 if (!strcmp(buf, "tcp")) {
1856 } else if (!strcmp(buf, "udp")) {
1862 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
1864 host_port = strtol(buf, &r, 0);
1868 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
1870 if (buf[0] == '\0') {
1871 pstrcpy(buf, sizeof(buf), "10.0.2.15");
1873 if (!inet_aton(buf, &guest_addr))
1876 guest_port = strtol(p, &r, 0);
1880 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
1881 fprintf(stderr, "qemu: could not set up redirection\n");
1886 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
1894 static void smb_exit(void)
1898 char filename[1024];
1900 /* erase all the files in the directory */
1901 d = opendir(smb_dir);
1906 if (strcmp(de->d_name, ".") != 0 &&
1907 strcmp(de->d_name, "..") != 0) {
1908 snprintf(filename, sizeof(filename), "%s/%s",
1909 smb_dir, de->d_name);
1917 /* automatic user mode samba server configuration */
1918 void net_slirp_smb(const char *exported_dir)
1920 char smb_conf[1024];
1921 char smb_cmdline[1024];
1924 if (!slirp_inited) {
1929 /* XXX: better tmp dir construction */
1930 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
1931 if (mkdir(smb_dir, 0700) < 0) {
1932 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
1935 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
1937 f = fopen(smb_conf, "w");
1939 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
1946 "socket address=127.0.0.1\n"
1947 "pid directory=%s\n"
1948 "lock directory=%s\n"
1949 "log file=%s/log.smbd\n"
1950 "smb passwd file=%s/smbpasswd\n"
1951 "security = share\n"
1966 snprintf(smb_cmdline, sizeof(smb_cmdline), "/usr/sbin/smbd -s %s",
1969 slirp_add_exec(0, smb_cmdline, 4, 139);
1972 #endif /* !defined(_WIN32) */
1974 #endif /* CONFIG_SLIRP */
1976 #if !defined(_WIN32)
1978 typedef struct TAPState {
1979 VLANClientState *vc;
1983 static void tap_receive(void *opaque, const uint8_t *buf, int size)
1985 TAPState *s = opaque;
1988 ret = write(s->fd, buf, size);
1989 if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
1996 static void tap_send(void *opaque)
1998 TAPState *s = opaque;
2002 size = read(s->fd, buf, sizeof(buf));
2004 qemu_send_packet(s->vc, buf, size);
2010 static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
2014 s = qemu_mallocz(sizeof(TAPState));
2018 s->vc = qemu_new_vlan_client(vlan, tap_receive, s);
2019 qemu_set_fd_handler(s->fd, tap_send, NULL, s);
2020 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
2025 static int tap_open(char *ifname, int ifname_size)
2031 fd = open("/dev/tap", O_RDWR);
2033 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
2038 dev = devname(s.st_rdev, S_IFCHR);
2039 pstrcpy(ifname, ifname_size, dev);
2041 fcntl(fd, F_SETFL, O_NONBLOCK);
2045 static int tap_open(char *ifname, int ifname_size)
2050 fd = open("/dev/net/tun", O_RDWR);
2052 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
2055 memset(&ifr, 0, sizeof(ifr));
2056 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
2057 if (ifname[0] != '\0')
2058 pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
2060 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
2061 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
2063 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
2067 pstrcpy(ifname, ifname_size, ifr.ifr_name);
2068 fcntl(fd, F_SETFL, O_NONBLOCK);
2073 static int net_tap_init(VLANState *vlan, const char *ifname1,
2074 const char *setup_script)
2077 int pid, status, fd;
2082 if (ifname1 != NULL)
2083 pstrcpy(ifname, sizeof(ifname), ifname1);
2086 fd = tap_open(ifname, sizeof(ifname));
2092 if (setup_script[0] != '\0') {
2093 /* try to launch network init script */
2098 *parg++ = (char *)setup_script;
2101 execv(setup_script, args);
2104 while (waitpid(pid, &status, 0) != pid);
2105 if (!WIFEXITED(status) ||
2106 WEXITSTATUS(status) != 0) {
2107 fprintf(stderr, "%s: could not launch network script\n",
2113 s = net_tap_fd_init(vlan, fd);
2116 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
2117 "tap: ifname=%s setup_script=%s", ifname, setup_script);
2121 /* network connection */
2122 typedef struct NetSocketState {
2123 VLANClientState *vc;
2125 int state; /* 0 = getting length, 1 = getting data */
2131 typedef struct NetSocketListenState {
2134 } NetSocketListenState;
2136 /* XXX: we consider we can send the whole packet without blocking */
2137 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
2139 NetSocketState *s = opaque;
2143 unix_write(s->fd, (const uint8_t *)&len, sizeof(len));
2144 unix_write(s->fd, buf, size);
2147 static void net_socket_send(void *opaque)
2149 NetSocketState *s = opaque;
2154 size = read(s->fd, buf1, sizeof(buf1));
2158 /* end of connection */
2159 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2164 /* reassemble a packet from the network */
2170 memcpy(s->buf + s->index, buf, l);
2174 if (s->index == 4) {
2176 s->packet_len = ntohl(*(uint32_t *)s->buf);
2182 l = s->packet_len - s->index;
2185 memcpy(s->buf + s->index, buf, l);
2189 if (s->index >= s->packet_len) {
2190 qemu_send_packet(s->vc, s->buf, s->packet_len);
2199 static void net_socket_connect(void *opaque)
2201 NetSocketState *s = opaque;
2202 qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
2205 static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
2209 s = qemu_mallocz(sizeof(NetSocketState));
2213 s->vc = qemu_new_vlan_client(vlan,
2214 net_socket_receive, s);
2215 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
2216 "socket: fd=%d", fd);
2218 net_socket_connect(s);
2220 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
2225 static void net_socket_accept(void *opaque)
2227 NetSocketListenState *s = opaque;
2229 struct sockaddr_in saddr;
2234 len = sizeof(saddr);
2235 fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
2236 if (fd < 0 && errno != EINTR) {
2238 } else if (fd >= 0) {
2242 s1 = net_socket_fd_init(s->vlan, fd, 1);
2246 snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
2247 "socket: connection from %s:%d",
2248 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
2252 static int net_socket_listen_init(VLANState *vlan, const char *host_str)
2254 NetSocketListenState *s;
2256 struct sockaddr_in saddr;
2258 if (parse_host_port(&saddr, host_str) < 0)
2261 s = qemu_mallocz(sizeof(NetSocketListenState));
2265 fd = socket(PF_INET, SOCK_STREAM, 0);
2270 fcntl(fd, F_SETFL, O_NONBLOCK);
2272 /* allow fast reuse */
2274 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val));
2276 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
2281 ret = listen(fd, 0);
2288 qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
2292 static int net_socket_connect_init(VLANState *vlan, const char *host_str)
2295 int fd, connected, ret;
2296 struct sockaddr_in saddr;
2298 if (parse_host_port(&saddr, host_str) < 0)
2301 fd = socket(PF_INET, SOCK_STREAM, 0);
2306 fcntl(fd, F_SETFL, O_NONBLOCK);
2310 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
2312 if (errno == EINTR || errno == EAGAIN) {
2313 } else if (errno == EINPROGRESS) {
2325 s = net_socket_fd_init(vlan, fd, connected);
2328 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
2329 "socket: connect to %s:%d",
2330 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
2334 #endif /* !_WIN32 */
2336 static int get_param_value(char *buf, int buf_size,
2337 const char *tag, const char *str)
2346 while (*p != '\0' && *p != '=') {
2347 if ((q - option) < sizeof(option) - 1)
2355 if (!strcmp(tag, option)) {
2357 while (*p != '\0' && *p != ',') {
2358 if ((q - buf) < buf_size - 1)
2365 while (*p != '\0' && *p != ',') {
2376 int net_client_init(const char *str)
2387 while (*p != '\0' && *p != ',') {
2388 if ((q - device) < sizeof(device) - 1)
2396 if (get_param_value(buf, sizeof(buf), "vlan", p)) {
2397 vlan_id = strtol(buf, NULL, 0);
2399 vlan = qemu_find_vlan(vlan_id);
2401 fprintf(stderr, "Could not create vlan %d\n", vlan_id);
2404 if (!strcmp(device, "nic")) {
2408 if (nb_nics >= MAX_NICS) {
2409 fprintf(stderr, "Too Many NICs\n");
2412 nd = &nd_table[nb_nics];
2413 macaddr = nd->macaddr;
2419 macaddr[5] = 0x56 + nb_nics;
2421 if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
2422 if (parse_macaddr(macaddr, buf) < 0) {
2423 fprintf(stderr, "invalid syntax for ethernet address\n");
2431 if (!strcmp(device, "none")) {
2432 /* does nothing. It is needed to signal that no network cards
2437 if (!strcmp(device, "user")) {
2438 ret = net_slirp_init(vlan);
2442 if (!strcmp(device, "tap")) {
2444 char setup_script[1024];
2446 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
2447 fd = strtol(buf, NULL, 0);
2449 if (net_tap_fd_init(vlan, fd))
2452 get_param_value(ifname, sizeof(ifname), "ifname", p);
2453 if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
2454 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
2456 ret = net_tap_init(vlan, ifname, setup_script);
2459 if (!strcmp(device, "socket")) {
2460 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
2462 fd = strtol(buf, NULL, 0);
2464 if (net_socket_fd_init(vlan, fd, 1))
2466 } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
2467 ret = net_socket_listen_init(vlan, buf);
2468 } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
2469 ret = net_socket_connect_init(vlan, buf);
2471 fprintf(stderr, "Unknown socket options: %s\n", p);
2477 fprintf(stderr, "Unknown network device: %s\n", device);
2481 fprintf(stderr, "Could not initialize device '%s'\n", device);
2487 void do_info_network(void)
2490 VLANClientState *vc;
2492 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
2493 term_printf("VLAN %d devices:\n", vlan->id);
2494 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
2495 term_printf(" %s\n", vc->info_str);
2499 /***********************************************************/
2502 static int usb_device_add(const char *devname)
2510 for(i = 0;i < MAX_VM_USB_PORTS; i++) {
2511 if (!vm_usb_ports[i]->dev)
2514 if (i == MAX_VM_USB_PORTS)
2517 if (strstart(devname, "host:", &p)) {
2518 dev = usb_host_device_open(p);
2521 } else if (!strcmp(devname, "mouse")) {
2522 dev = usb_mouse_init();
2528 usb_attach(vm_usb_ports[i], dev);
2532 static int usb_device_del(const char *devname)
2535 int bus_num, addr, i;
2541 p = strchr(devname, '.');
2544 bus_num = strtoul(devname, NULL, 0);
2545 addr = strtoul(p + 1, NULL, 0);
2548 for(i = 0;i < MAX_VM_USB_PORTS; i++) {
2549 dev = vm_usb_ports[i]->dev;
2550 if (dev && dev->addr == addr)
2553 if (i == MAX_VM_USB_PORTS)
2555 usb_attach(vm_usb_ports[i], NULL);
2559 void do_usb_add(const char *devname)
2562 ret = usb_device_add(devname);
2564 term_printf("Could not add USB device '%s'\n", devname);
2567 void do_usb_del(const char *devname)
2570 ret = usb_device_del(devname);
2572 term_printf("Could not remove USB device '%s'\n", devname);
2579 const char *speed_str;
2582 term_printf("USB support not enabled\n");
2586 for(i = 0; i < MAX_VM_USB_PORTS; i++) {
2587 dev = vm_usb_ports[i]->dev;
2589 term_printf("Hub port %d:\n", i);
2590 switch(dev->speed) {
2594 case USB_SPEED_FULL:
2597 case USB_SPEED_HIGH:
2604 term_printf(" Device %d.%d, speed %s Mb/s\n",
2605 0, dev->addr, speed_str);
2610 /***********************************************************/
2613 static char *pid_filename;
2615 /* Remove PID file. Called on normal exit */
2617 static void remove_pidfile(void)
2619 unlink (pid_filename);
2622 static void create_pidfile(const char *filename)
2624 struct stat pidstat;
2627 /* Try to write our PID to the named file */
2628 if (stat(filename, &pidstat) < 0) {
2629 if (errno == ENOENT) {
2630 if ((f = fopen (filename, "w")) == NULL) {
2631 perror("Opening pidfile");
2634 fprintf(f, "%d\n", getpid());
2636 pid_filename = qemu_strdup(filename);
2637 if (!pid_filename) {
2638 fprintf(stderr, "Could not save PID filename");
2641 atexit(remove_pidfile);
2644 fprintf(stderr, "%s already exists. Remove it and try again.\n",
2650 /***********************************************************/
2653 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
2657 static void dumb_resize(DisplayState *ds, int w, int h)
2661 static void dumb_refresh(DisplayState *ds)
2663 vga_update_display();
2666 void dumb_display_init(DisplayState *ds)
2671 ds->dpy_update = dumb_update;
2672 ds->dpy_resize = dumb_resize;
2673 ds->dpy_refresh = dumb_refresh;
2676 #if !defined(CONFIG_SOFTMMU)
2677 /***********************************************************/
2678 /* cpu signal handler */
2679 static void host_segv_handler(int host_signum, siginfo_t *info,
2682 if (cpu_signal_handler(host_signum, info, puc))
2684 if (stdio_nb_clients > 0)
2690 /***********************************************************/
2693 #define MAX_IO_HANDLERS 64
2695 typedef struct IOHandlerRecord {
2697 IOCanRWHandler *fd_read_poll;
2699 IOHandler *fd_write;
2701 /* temporary data */
2703 struct IOHandlerRecord *next;
2706 static IOHandlerRecord *first_io_handler;
2708 /* XXX: fd_read_poll should be suppressed, but an API change is
2709 necessary in the character devices to suppress fd_can_read(). */
2710 int qemu_set_fd_handler2(int fd,
2711 IOCanRWHandler *fd_read_poll,
2713 IOHandler *fd_write,
2716 IOHandlerRecord **pioh, *ioh;
2718 if (!fd_read && !fd_write) {
2719 pioh = &first_io_handler;
2724 if (ioh->fd == fd) {
2731 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2735 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
2738 ioh->next = first_io_handler;
2739 first_io_handler = ioh;
2742 ioh->fd_read_poll = fd_read_poll;
2743 ioh->fd_read = fd_read;
2744 ioh->fd_write = fd_write;
2745 ioh->opaque = opaque;
2750 int qemu_set_fd_handler(int fd,
2752 IOHandler *fd_write,
2755 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
2758 /***********************************************************/
2759 /* savevm/loadvm support */
2761 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
2763 fwrite(buf, 1, size, f);
2766 void qemu_put_byte(QEMUFile *f, int v)
2771 void qemu_put_be16(QEMUFile *f, unsigned int v)
2773 qemu_put_byte(f, v >> 8);
2774 qemu_put_byte(f, v);
2777 void qemu_put_be32(QEMUFile *f, unsigned int v)
2779 qemu_put_byte(f, v >> 24);
2780 qemu_put_byte(f, v >> 16);
2781 qemu_put_byte(f, v >> 8);
2782 qemu_put_byte(f, v);
2785 void qemu_put_be64(QEMUFile *f, uint64_t v)
2787 qemu_put_be32(f, v >> 32);
2788 qemu_put_be32(f, v);
2791 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size)
2793 return fread(buf, 1, size, f);
2796 int qemu_get_byte(QEMUFile *f)
2806 unsigned int qemu_get_be16(QEMUFile *f)
2809 v = qemu_get_byte(f) << 8;
2810 v |= qemu_get_byte(f);
2814 unsigned int qemu_get_be32(QEMUFile *f)
2817 v = qemu_get_byte(f) << 24;
2818 v |= qemu_get_byte(f) << 16;
2819 v |= qemu_get_byte(f) << 8;
2820 v |= qemu_get_byte(f);
2824 uint64_t qemu_get_be64(QEMUFile *f)
2827 v = (uint64_t)qemu_get_be32(f) << 32;
2828 v |= qemu_get_be32(f);
2832 int64_t qemu_ftell(QEMUFile *f)
2837 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
2839 if (fseek(f, pos, whence) < 0)
2844 typedef struct SaveStateEntry {
2848 SaveStateHandler *save_state;
2849 LoadStateHandler *load_state;
2851 struct SaveStateEntry *next;
2854 static SaveStateEntry *first_se;
2856 int register_savevm(const char *idstr,
2859 SaveStateHandler *save_state,
2860 LoadStateHandler *load_state,
2863 SaveStateEntry *se, **pse;
2865 se = qemu_malloc(sizeof(SaveStateEntry));
2868 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
2869 se->instance_id = instance_id;
2870 se->version_id = version_id;
2871 se->save_state = save_state;
2872 se->load_state = load_state;
2873 se->opaque = opaque;
2876 /* add at the end of list */
2878 while (*pse != NULL)
2879 pse = &(*pse)->next;
2884 #define QEMU_VM_FILE_MAGIC 0x5145564d
2885 #define QEMU_VM_FILE_VERSION 0x00000001
2887 int qemu_savevm(const char *filename)
2891 int len, len_pos, cur_pos, saved_vm_running, ret;
2893 saved_vm_running = vm_running;
2896 f = fopen(filename, "wb");
2902 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
2903 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
2905 for(se = first_se; se != NULL; se = se->next) {
2907 len = strlen(se->idstr);
2908 qemu_put_byte(f, len);
2909 qemu_put_buffer(f, se->idstr, len);
2911 qemu_put_be32(f, se->instance_id);
2912 qemu_put_be32(f, se->version_id);
2914 /* record size: filled later */
2916 qemu_put_be32(f, 0);
2918 se->save_state(f, se->opaque);
2920 /* fill record size */
2922 len = ftell(f) - len_pos - 4;
2923 fseek(f, len_pos, SEEK_SET);
2924 qemu_put_be32(f, len);
2925 fseek(f, cur_pos, SEEK_SET);
2931 if (saved_vm_running)
2936 static SaveStateEntry *find_se(const char *idstr, int instance_id)
2940 for(se = first_se; se != NULL; se = se->next) {
2941 if (!strcmp(se->idstr, idstr) &&
2942 instance_id == se->instance_id)
2948 int qemu_loadvm(const char *filename)
2952 int len, cur_pos, ret, instance_id, record_len, version_id;
2953 int saved_vm_running;
2957 saved_vm_running = vm_running;
2960 f = fopen(filename, "rb");
2966 v = qemu_get_be32(f);
2967 if (v != QEMU_VM_FILE_MAGIC)
2969 v = qemu_get_be32(f);
2970 if (v != QEMU_VM_FILE_VERSION) {
2977 len = qemu_get_byte(f);
2980 qemu_get_buffer(f, idstr, len);
2982 instance_id = qemu_get_be32(f);
2983 version_id = qemu_get_be32(f);
2984 record_len = qemu_get_be32(f);
2986 printf("idstr=%s instance=0x%x version=%d len=%d\n",
2987 idstr, instance_id, version_id, record_len);
2990 se = find_se(idstr, instance_id);
2992 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
2993 instance_id, idstr);
2995 ret = se->load_state(f, se->opaque, version_id);
2997 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
2998 instance_id, idstr);
3001 /* always seek to exact end of record */
3002 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
3007 if (saved_vm_running)
3012 /***********************************************************/
3013 /* cpu save/restore */
3015 #if defined(TARGET_I386)
3017 static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
3019 qemu_put_be32(f, dt->selector);
3020 qemu_put_betl(f, dt->base);
3021 qemu_put_be32(f, dt->limit);
3022 qemu_put_be32(f, dt->flags);
3025 static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
3027 dt->selector = qemu_get_be32(f);
3028 dt->base = qemu_get_betl(f);
3029 dt->limit = qemu_get_be32(f);
3030 dt->flags = qemu_get_be32(f);
3033 void cpu_save(QEMUFile *f, void *opaque)
3035 CPUState *env = opaque;
3036 uint16_t fptag, fpus, fpuc, fpregs_format;
3040 for(i = 0; i < CPU_NB_REGS; i++)
3041 qemu_put_betls(f, &env->regs[i]);
3042 qemu_put_betls(f, &env->eip);
3043 qemu_put_betls(f, &env->eflags);
3044 hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
3045 qemu_put_be32s(f, &hflags);
3049 fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
3051 for(i = 0; i < 8; i++) {
3052 fptag |= ((!env->fptags[i]) << i);
3055 qemu_put_be16s(f, &fpuc);
3056 qemu_put_be16s(f, &fpus);
3057 qemu_put_be16s(f, &fptag);
3059 #ifdef USE_X86LDOUBLE
3064 qemu_put_be16s(f, &fpregs_format);
3066 for(i = 0; i < 8; i++) {
3067 #ifdef USE_X86LDOUBLE
3071 /* we save the real CPU data (in case of MMX usage only 'mant'
3072 contains the MMX register */
3073 cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
3074 qemu_put_be64(f, mant);
3075 qemu_put_be16(f, exp);
3078 /* if we use doubles for float emulation, we save the doubles to
3079 avoid losing information in case of MMX usage. It can give
3080 problems if the image is restored on a CPU where long
3081 doubles are used instead. */
3082 qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
3086 for(i = 0; i < 6; i++)
3087 cpu_put_seg(f, &env->segs[i]);
3088 cpu_put_seg(f, &env->ldt);
3089 cpu_put_seg(f, &env->tr);
3090 cpu_put_seg(f, &env->gdt);
3091 cpu_put_seg(f, &env->idt);
3093 qemu_put_be32s(f, &env->sysenter_cs);
3094 qemu_put_be32s(f, &env->sysenter_esp);
3095 qemu_put_be32s(f, &env->sysenter_eip);
3097 qemu_put_betls(f, &env->cr[0]);
3098 qemu_put_betls(f, &env->cr[2]);
3099 qemu_put_betls(f, &env->cr[3]);
3100 qemu_put_betls(f, &env->cr[4]);
3102 for(i = 0; i < 8; i++)
3103 qemu_put_betls(f, &env->dr[i]);
3106 qemu_put_be32s(f, &env->a20_mask);
3109 qemu_put_be32s(f, &env->mxcsr);
3110 for(i = 0; i < CPU_NB_REGS; i++) {
3111 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
3112 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
3115 #ifdef TARGET_X86_64
3116 qemu_put_be64s(f, &env->efer);
3117 qemu_put_be64s(f, &env->star);
3118 qemu_put_be64s(f, &env->lstar);
3119 qemu_put_be64s(f, &env->cstar);
3120 qemu_put_be64s(f, &env->fmask);
3121 qemu_put_be64s(f, &env->kernelgsbase);
3125 #ifdef USE_X86LDOUBLE
3126 /* XXX: add that in a FPU generic layer */
3127 union x86_longdouble {
3132 #define MANTD1(fp) (fp & ((1LL << 52) - 1))
3133 #define EXPBIAS1 1023
3134 #define EXPD1(fp) ((fp >> 52) & 0x7FF)
3135 #define SIGND1(fp) ((fp >> 32) & 0x80000000)
3137 static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
3141 p->mant = (MANTD1(temp) << 11) | (1LL << 63);
3142 /* exponent + sign */
3143 e = EXPD1(temp) - EXPBIAS1 + 16383;
3144 e |= SIGND1(temp) >> 16;
3149 int cpu_load(QEMUFile *f, void *opaque, int version_id)
3151 CPUState *env = opaque;
3154 uint16_t fpus, fpuc, fptag, fpregs_format;
3156 if (version_id != 3)
3158 for(i = 0; i < CPU_NB_REGS; i++)
3159 qemu_get_betls(f, &env->regs[i]);
3160 qemu_get_betls(f, &env->eip);
3161 qemu_get_betls(f, &env->eflags);
3162 qemu_get_be32s(f, &hflags);
3164 qemu_get_be16s(f, &fpuc);
3165 qemu_get_be16s(f, &fpus);
3166 qemu_get_be16s(f, &fptag);
3167 qemu_get_be16s(f, &fpregs_format);
3169 /* NOTE: we cannot always restore the FPU state if the image come
3170 from a host with a different 'USE_X86LDOUBLE' define. We guess
3171 if we are in an MMX state to restore correctly in that case. */
3172 guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
3173 for(i = 0; i < 8; i++) {
3177 switch(fpregs_format) {
3179 mant = qemu_get_be64(f);
3180 exp = qemu_get_be16(f);
3181 #ifdef USE_X86LDOUBLE
3182 env->fpregs[i].d = cpu_set_fp80(mant, exp);
3184 /* difficult case */
3186 env->fpregs[i].mmx.MMX_Q(0) = mant;
3188 env->fpregs[i].d = cpu_set_fp80(mant, exp);
3192 mant = qemu_get_be64(f);
3193 #ifdef USE_X86LDOUBLE
3195 union x86_longdouble *p;
3196 /* difficult case */
3197 p = (void *)&env->fpregs[i];
3202 fp64_to_fp80(p, mant);
3206 env->fpregs[i].mmx.MMX_Q(0) = mant;
3215 /* XXX: restore FPU round state */
3216 env->fpstt = (fpus >> 11) & 7;
3217 env->fpus = fpus & ~0x3800;
3219 for(i = 0; i < 8; i++) {
3220 env->fptags[i] = (fptag >> i) & 1;
3223 for(i = 0; i < 6; i++)
3224 cpu_get_seg(f, &env->segs[i]);
3225 cpu_get_seg(f, &env->ldt);
3226 cpu_get_seg(f, &env->tr);
3227 cpu_get_seg(f, &env->gdt);
3228 cpu_get_seg(f, &env->idt);
3230 qemu_get_be32s(f, &env->sysenter_cs);
3231 qemu_get_be32s(f, &env->sysenter_esp);
3232 qemu_get_be32s(f, &env->sysenter_eip);
3234 qemu_get_betls(f, &env->cr[0]);
3235 qemu_get_betls(f, &env->cr[2]);
3236 qemu_get_betls(f, &env->cr[3]);
3237 qemu_get_betls(f, &env->cr[4]);
3239 for(i = 0; i < 8; i++)
3240 qemu_get_betls(f, &env->dr[i]);
3243 qemu_get_be32s(f, &env->a20_mask);
3245 qemu_get_be32s(f, &env->mxcsr);
3246 for(i = 0; i < CPU_NB_REGS; i++) {
3247 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
3248 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
3251 #ifdef TARGET_X86_64
3252 qemu_get_be64s(f, &env->efer);
3253 qemu_get_be64s(f, &env->star);
3254 qemu_get_be64s(f, &env->lstar);
3255 qemu_get_be64s(f, &env->cstar);
3256 qemu_get_be64s(f, &env->fmask);
3257 qemu_get_be64s(f, &env->kernelgsbase);
3260 /* XXX: compute hflags from scratch, except for CPL and IIF */
3261 env->hflags = hflags;
3266 #elif defined(TARGET_PPC)
3267 void cpu_save(QEMUFile *f, void *opaque)
3271 int cpu_load(QEMUFile *f, void *opaque, int version_id)
3276 #elif defined(TARGET_MIPS)
3277 void cpu_save(QEMUFile *f, void *opaque)
3281 int cpu_load(QEMUFile *f, void *opaque, int version_id)
3286 #elif defined(TARGET_SPARC)
3287 void cpu_save(QEMUFile *f, void *opaque)
3289 CPUState *env = opaque;
3293 for(i = 0; i < 8; i++)
3294 qemu_put_betls(f, &env->gregs[i]);
3295 for(i = 0; i < NWINDOWS * 16; i++)
3296 qemu_put_betls(f, &env->regbase[i]);
3299 for(i = 0; i < TARGET_FPREGS; i++) {
3305 qemu_put_betl(f, u.i);
3308 qemu_put_betls(f, &env->pc);
3309 qemu_put_betls(f, &env->npc);
3310 qemu_put_betls(f, &env->y);
3312 qemu_put_be32(f, tmp);
3313 qemu_put_betls(f, &env->fsr);
3314 qemu_put_betls(f, &env->tbr);
3315 #ifndef TARGET_SPARC64
3316 qemu_put_be32s(f, &env->wim);
3318 for(i = 0; i < 16; i++)
3319 qemu_put_be32s(f, &env->mmuregs[i]);
3323 int cpu_load(QEMUFile *f, void *opaque, int version_id)
3325 CPUState *env = opaque;
3329 for(i = 0; i < 8; i++)
3330 qemu_get_betls(f, &env->gregs[i]);
3331 for(i = 0; i < NWINDOWS * 16; i++)
3332 qemu_get_betls(f, &env->regbase[i]);
3335 for(i = 0; i < TARGET_FPREGS; i++) {
3340 u.i = qemu_get_betl(f);
3344 qemu_get_betls(f, &env->pc);
3345 qemu_get_betls(f, &env->npc);
3346 qemu_get_betls(f, &env->y);
3347 tmp = qemu_get_be32(f);
3348 env->cwp = 0; /* needed to ensure that the wrapping registers are
3349 correctly updated */
3351 qemu_get_betls(f, &env->fsr);
3352 qemu_get_betls(f, &env->tbr);
3353 #ifndef TARGET_SPARC64
3354 qemu_get_be32s(f, &env->wim);
3356 for(i = 0; i < 16; i++)
3357 qemu_get_be32s(f, &env->mmuregs[i]);
3363 #elif defined(TARGET_ARM)
3365 /* ??? Need to implement these. */
3366 void cpu_save(QEMUFile *f, void *opaque)
3370 int cpu_load(QEMUFile *f, void *opaque, int version_id)
3377 #warning No CPU save/restore functions
3381 /***********************************************************/
3382 /* ram save/restore */
3384 /* we just avoid storing empty pages */
3385 static void ram_put_page(QEMUFile *f, const uint8_t *buf, int len)
3390 for(i = 1; i < len; i++) {
3394 qemu_put_byte(f, 1);
3395 qemu_put_byte(f, v);
3398 qemu_put_byte(f, 0);
3399 qemu_put_buffer(f, buf, len);
3402 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
3406 v = qemu_get_byte(f);
3409 if (qemu_get_buffer(f, buf, len) != len)
3413 v = qemu_get_byte(f);
3414 memset(buf, v, len);
3422 static void ram_save(QEMUFile *f, void *opaque)
3425 qemu_put_be32(f, phys_ram_size);
3426 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
3427 ram_put_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
3431 static int ram_load(QEMUFile *f, void *opaque, int version_id)
3435 if (version_id != 1)
3437 if (qemu_get_be32(f) != phys_ram_size)
3439 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
3440 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
3447 /***********************************************************/
3448 /* machine registration */
3450 QEMUMachine *first_machine = NULL;
3452 int qemu_register_machine(QEMUMachine *m)
3455 pm = &first_machine;
3463 QEMUMachine *find_machine(const char *name)
3467 for(m = first_machine; m != NULL; m = m->next) {
3468 if (!strcmp(m->name, name))
3474 /***********************************************************/
3475 /* main execution loop */
3477 void gui_update(void *opaque)
3479 display_state.dpy_refresh(&display_state);
3480 qemu_mod_timer(gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
3483 struct vm_change_state_entry {
3484 VMChangeStateHandler *cb;
3486 LIST_ENTRY (vm_change_state_entry) entries;
3489 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3491 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3494 VMChangeStateEntry *e;
3496 e = qemu_mallocz(sizeof (*e));
3502 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3506 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3508 LIST_REMOVE (e, entries);
3512 static void vm_state_notify(int running)
3514 VMChangeStateEntry *e;
3516 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3517 e->cb(e->opaque, running);
3521 /* XXX: support several handlers */
3522 static VMStopHandler *vm_stop_cb;
3523 static void *vm_stop_opaque;
3525 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
3528 vm_stop_opaque = opaque;
3532 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
3546 void vm_stop(int reason)
3549 cpu_disable_ticks();
3553 vm_stop_cb(vm_stop_opaque, reason);
3560 /* reset/shutdown handler */
3562 typedef struct QEMUResetEntry {
3563 QEMUResetHandler *func;
3565 struct QEMUResetEntry *next;
3568 static QEMUResetEntry *first_reset_entry;
3569 static int reset_requested;
3570 static int shutdown_requested;
3571 static int powerdown_requested;
3573 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
3575 QEMUResetEntry **pre, *re;
3577 pre = &first_reset_entry;
3578 while (*pre != NULL)
3579 pre = &(*pre)->next;
3580 re = qemu_mallocz(sizeof(QEMUResetEntry));
3582 re->opaque = opaque;
3587 void qemu_system_reset(void)
3591 /* reset all devices */
3592 for(re = first_reset_entry; re != NULL; re = re->next) {
3593 re->func(re->opaque);
3597 void qemu_system_reset_request(void)
3599 reset_requested = 1;
3601 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
3604 void qemu_system_shutdown_request(void)
3606 shutdown_requested = 1;
3608 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
3611 void qemu_system_powerdown_request(void)
3613 powerdown_requested = 1;
3615 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
3618 void main_loop_wait(int timeout)
3621 struct pollfd ufds[MAX_IO_HANDLERS + 1], *pf;
3622 IOHandlerRecord *ioh, *ioh_next;
3630 /* poll any events */
3631 /* XXX: separate device handlers from system ones */
3633 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3637 (!ioh->fd_read_poll ||
3638 ioh->fd_read_poll(ioh->opaque) != 0)) {
3639 pf->events |= POLLIN;
3641 if (ioh->fd_write) {
3642 pf->events |= POLLOUT;
3648 ret = poll(ufds, pf - ufds, timeout);
3650 /* XXX: better handling of removal */
3651 for(ioh = first_io_handler; ioh != NULL; ioh = ioh_next) {
3652 ioh_next = ioh->next;
3654 if (pf->revents & POLLIN) {
3655 ioh->fd_read(ioh->opaque);
3657 if (pf->revents & POLLOUT) {
3658 ioh->fd_write(ioh->opaque);
3662 #endif /* !defined(_WIN32) */
3663 #if defined(CONFIG_SLIRP)
3664 /* XXX: merge with poll() */
3666 fd_set rfds, wfds, xfds;
3674 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
3677 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
3679 slirp_select_poll(&rfds, &wfds, &xfds);
3685 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
3686 qemu_get_clock(vm_clock));
3687 /* run dma transfers, if any */
3691 /* real time timers */
3692 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
3693 qemu_get_clock(rt_clock));
3696 static CPUState *cur_cpu;
3703 cur_cpu = first_cpu;
3710 env = env->next_cpu;
3713 ret = cpu_exec(env);
3714 if (ret != EXCP_HALTED)
3716 /* all CPUs are halted ? */
3717 if (env == cur_cpu) {
3724 if (shutdown_requested) {
3725 ret = EXCP_INTERRUPT;
3728 if (reset_requested) {
3729 reset_requested = 0;
3730 qemu_system_reset();
3731 ret = EXCP_INTERRUPT;
3733 if (powerdown_requested) {
3734 powerdown_requested = 0;
3735 qemu_system_powerdown();
3736 ret = EXCP_INTERRUPT;
3738 if (ret == EXCP_DEBUG) {
3739 vm_stop(EXCP_DEBUG);
3741 /* if hlt instruction, we wait until the next IRQ */
3742 /* XXX: use timeout computed from timers */
3743 if (ret == EXCP_HLT)
3750 main_loop_wait(timeout);
3752 cpu_disable_ticks();
3758 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2005 Fabrice Bellard\n"
3759 "usage: %s [options] [disk_image]\n"
3761 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
3763 "Standard options:\n"
3764 "-M machine select emulated machine (-M ? for list)\n"
3765 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
3766 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
3767 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
3768 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
3769 "-boot [a|c|d] boot on floppy (a), hard disk (c) or CD-ROM (d)\n"
3770 "-snapshot write to temporary files instead of disk image files\n"
3771 "-m megs set virtual RAM size to megs MB [default=%d]\n"
3772 "-nographic disable graphical output and redirect serial I/Os to console\n"
3774 "-k language use keyboard layout (for example \"fr\" for French)\n"
3777 "-enable-audio enable audio support, and all the sound cars\n"
3778 "-audio-help print list of audio drivers and their options\n"
3779 "-soundhw c1,... enable audio support\n"
3780 " and only specified sound cards (comma separated list)\n"
3781 " use -soundhw ? to get the list of supported cards\n"
3783 "-localtime set the real time clock to local time [default=utc]\n"
3784 "-full-screen start in full screen\n"
3786 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
3788 "-usb enable the USB driver (will be the default soon)\n"
3789 "-usbdevice name add the host or guest USB device 'name'\n"
3790 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
3791 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
3794 "Network options:\n"
3795 "-net nic[,vlan=n][,macaddr=addr]\n"
3796 " create a new Network Interface Card and connect it to VLAN 'n'\n"
3798 "-net user[,vlan=n]\n"
3799 " connect the user mode network stack to VLAN 'n'\n"
3802 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file]\n"
3803 " connect the host TAP network interface to VLAN 'n' and use\n"
3804 " the network script 'file' (default=%s);\n"
3805 " use 'fd=h' to connect to an already opened TAP interface\n"
3806 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
3807 " connect the vlan 'n' to another VLAN using a socket connection\n"
3809 "-net none use it alone to have zero network devices; if no -net option\n"
3810 " is provided, the default is '-net nic -net user'\n"
3813 "-tftp prefix allow tftp access to files starting with prefix [-net user]\n"
3815 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
3817 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
3818 " redirect TCP or UDP connections from host to guest [-net user]\n"
3821 "Linux boot specific:\n"
3822 "-kernel bzImage use 'bzImage' as kernel image\n"
3823 "-append cmdline use 'cmdline' as kernel command line\n"
3824 "-initrd file use 'file' as initial ram disk\n"
3826 "Debug/Expert options:\n"
3827 "-monitor dev redirect the monitor to char device 'dev'\n"
3828 "-serial dev redirect the serial port to char device 'dev'\n"
3829 "-parallel dev redirect the parallel port to char device 'dev'\n"
3830 "-pidfile file Write PID to 'file'\n"
3831 "-S freeze CPU at startup (use 'c' to start execution)\n"
3832 "-s wait gdb connection to port %d\n"
3833 "-p port change gdb connection port\n"
3834 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
3835 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
3836 " translation (t=none or lba) (usually qemu can guess them)\n"
3837 "-L path set the directory for the BIOS and VGA BIOS\n"
3839 "-no-kqemu disable KQEMU kernel module usage\n"
3841 #ifdef USE_CODE_COPY
3842 "-no-code-copy disable code copy acceleration\n"
3845 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
3846 " (default is CL-GD5446 PCI VGA)\n"
3848 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
3850 "During emulation, the following keys are useful:\n"
3851 "ctrl-alt-f toggle full screen\n"
3852 "ctrl-alt-n switch to virtual console 'n'\n"
3853 "ctrl-alt toggle mouse and keyboard grab\n"
3855 "When using -nographic, press 'ctrl-a h' to get some help.\n"
3857 #ifdef CONFIG_SOFTMMU
3864 DEFAULT_NETWORK_SCRIPT,
3866 DEFAULT_GDBSTUB_PORT,
3868 #ifndef CONFIG_SOFTMMU
3870 "NOTE: this version of QEMU is faster but it needs slightly patched OSes to\n"
3871 "work. Please use the 'qemu' executable to have a more accurate (but slower)\n"
3877 #define HAS_ARG 0x0001
3891 QEMU_OPTION_snapshot,
3893 QEMU_OPTION_nographic,
3895 QEMU_OPTION_enable_audio,
3896 QEMU_OPTION_audio_help,
3897 QEMU_OPTION_soundhw,
3915 QEMU_OPTION_no_code_copy,
3917 QEMU_OPTION_localtime,
3918 QEMU_OPTION_cirrusvga,
3920 QEMU_OPTION_std_vga,
3921 QEMU_OPTION_monitor,
3923 QEMU_OPTION_parallel,
3925 QEMU_OPTION_full_screen,
3926 QEMU_OPTION_pidfile,
3927 QEMU_OPTION_no_kqemu,
3928 QEMU_OPTION_win2k_hack,
3930 QEMU_OPTION_usbdevice,
3934 typedef struct QEMUOption {
3940 const QEMUOption qemu_options[] = {
3941 { "h", 0, QEMU_OPTION_h },
3943 { "M", HAS_ARG, QEMU_OPTION_M },
3944 { "fda", HAS_ARG, QEMU_OPTION_fda },
3945 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
3946 { "hda", HAS_ARG, QEMU_OPTION_hda },
3947 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
3948 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
3949 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
3950 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
3951 { "boot", HAS_ARG, QEMU_OPTION_boot },
3952 { "snapshot", 0, QEMU_OPTION_snapshot },
3953 { "m", HAS_ARG, QEMU_OPTION_m },
3954 { "nographic", 0, QEMU_OPTION_nographic },
3955 { "k", HAS_ARG, QEMU_OPTION_k },
3957 { "enable-audio", 0, QEMU_OPTION_enable_audio },
3958 { "audio-help", 0, QEMU_OPTION_audio_help },
3959 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
3962 { "net", HAS_ARG, QEMU_OPTION_net},
3964 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
3966 { "smb", HAS_ARG, QEMU_OPTION_smb },
3968 { "redir", HAS_ARG, QEMU_OPTION_redir },
3971 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
3972 { "append", HAS_ARG, QEMU_OPTION_append },
3973 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
3975 { "S", 0, QEMU_OPTION_S },
3976 { "s", 0, QEMU_OPTION_s },
3977 { "p", HAS_ARG, QEMU_OPTION_p },
3978 { "d", HAS_ARG, QEMU_OPTION_d },
3979 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
3980 { "L", HAS_ARG, QEMU_OPTION_L },
3981 { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
3983 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
3985 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
3986 { "g", 1, QEMU_OPTION_g },
3988 { "localtime", 0, QEMU_OPTION_localtime },
3989 { "std-vga", 0, QEMU_OPTION_std_vga },
3990 { "monitor", 1, QEMU_OPTION_monitor },
3991 { "serial", 1, QEMU_OPTION_serial },
3992 { "parallel", 1, QEMU_OPTION_parallel },
3993 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
3994 { "full-screen", 0, QEMU_OPTION_full_screen },
3995 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
3996 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
3997 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
3998 { "smp", HAS_ARG, QEMU_OPTION_smp },
4000 /* temporary options */
4001 { "usb", 0, QEMU_OPTION_usb },
4002 { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
4006 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
4008 /* this stack is only used during signal handling */
4009 #define SIGNAL_STACK_SIZE 32768
4011 static uint8_t *signal_stack;
4015 /* password input */
4017 static BlockDriverState *get_bdrv(int index)
4019 BlockDriverState *bs;
4022 bs = bs_table[index];
4023 } else if (index < 6) {
4024 bs = fd_table[index - 4];
4031 static void read_passwords(void)
4033 BlockDriverState *bs;
4037 for(i = 0; i < 6; i++) {
4039 if (bs && bdrv_is_encrypted(bs)) {
4040 term_printf("%s is encrypted.\n", bdrv_get_device_name(bs));
4041 for(j = 0; j < 3; j++) {
4042 monitor_readline("Password: ",
4043 1, password, sizeof(password));
4044 if (bdrv_set_key(bs, password) == 0)
4046 term_printf("invalid password\n");
4052 /* XXX: currently we cannot use simultaneously different CPUs */
4053 void register_machines(void)
4055 #if defined(TARGET_I386)
4056 qemu_register_machine(&pc_machine);
4057 qemu_register_machine(&isapc_machine);
4058 #elif defined(TARGET_PPC)
4059 qemu_register_machine(&heathrow_machine);
4060 qemu_register_machine(&core99_machine);
4061 qemu_register_machine(&prep_machine);
4062 #elif defined(TARGET_MIPS)
4063 qemu_register_machine(&mips_machine);
4064 #elif defined(TARGET_SPARC)
4065 #ifdef TARGET_SPARC64
4066 qemu_register_machine(&sun4u_machine);
4068 qemu_register_machine(&sun4m_machine);
4070 #elif defined(TARGET_ARM)
4071 qemu_register_machine(&integratorcp_machine);
4073 #error unsupported CPU
4078 static void select_soundhw (const char *optarg)
4080 if (*optarg == '?') {
4082 printf ("Valid sound card names (comma separated):\n");
4083 printf ("sb16 Creative Sound Blaster 16\n");
4086 printf ("adlib Yamaha YMF262 (OPL3)\n");
4088 printf ("adlib Yamaha YM3812 (OPL2)\n");
4092 printf ("gus Gravis Ultrasound GF1\n");
4094 printf ("es1370 ENSONIQ AudioPCI ES1370\n");
4095 exit (*optarg != '?');
4102 { "sb16", &sb16_enabled },
4104 { "adlib", &adlib_enabled },
4107 { "gus", &gus_enabled },
4109 { "es1370", &es1370_enabled },
4111 size_t tablen, l, i;
4117 tablen = sizeof (soundhw_tab) / sizeof (soundhw_tab[0]);
4120 e = strchr (p, ',');
4121 l = !e ? strlen (p) : (size_t) (e - p);
4122 for (i = 0; i < tablen; ++i) {
4123 if (!strncmp (soundhw_tab[i].name, p, l)) {
4125 *soundhw_tab[i].enabledp = 1;
4132 "Unknown sound card name (too big to show)\n");
4135 fprintf (stderr, "Unknown sound card name `%.*s'\n",
4140 p += l + (e != NULL);
4144 goto show_valid_cards;
4149 #define MAX_NET_CLIENTS 32
4151 int main(int argc, char **argv)
4153 #ifdef CONFIG_GDBSTUB
4154 int use_gdbstub, gdbstub_port;
4157 int snapshot, linux_boot;
4158 const char *initrd_filename;
4159 const char *hd_filename[MAX_DISKS], *fd_filename[MAX_FD];
4160 const char *kernel_filename, *kernel_cmdline;
4161 DisplayState *ds = &display_state;
4162 int cyls, heads, secs, translation;
4163 int start_emulation = 1;
4164 char net_clients[MAX_NET_CLIENTS][256];
4167 const char *r, *optarg;
4168 CharDriverState *monitor_hd;
4169 char monitor_device[128];
4170 char serial_devices[MAX_SERIAL_PORTS][128];
4171 int serial_device_index;
4172 char parallel_devices[MAX_PARALLEL_PORTS][128];
4173 int parallel_device_index;
4174 const char *loadvm = NULL;
4175 QEMUMachine *machine;
4176 char usb_devices[MAX_VM_USB_PORTS][128];
4177 int usb_devices_index;
4179 LIST_INIT (&vm_change_state_head);
4180 #if !defined(CONFIG_SOFTMMU)
4181 /* we never want that malloc() uses mmap() */
4182 mallopt(M_MMAP_THRESHOLD, 4096 * 1024);
4184 register_machines();
4185 machine = first_machine;
4186 initrd_filename = NULL;
4187 for(i = 0; i < MAX_FD; i++)
4188 fd_filename[i] = NULL;
4189 for(i = 0; i < MAX_DISKS; i++)
4190 hd_filename[i] = NULL;
4191 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
4192 vga_ram_size = VGA_RAM_SIZE;
4193 bios_size = BIOS_SIZE;
4194 #ifdef CONFIG_GDBSTUB
4196 gdbstub_port = DEFAULT_GDBSTUB_PORT;
4200 kernel_filename = NULL;
4201 kernel_cmdline = "";
4207 cyls = heads = secs = 0;
4208 translation = BIOS_ATA_TRANSLATION_AUTO;
4209 pstrcpy(monitor_device, sizeof(monitor_device), "vc");
4211 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
4212 for(i = 1; i < MAX_SERIAL_PORTS; i++)
4213 serial_devices[i][0] = '\0';
4214 serial_device_index = 0;
4216 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
4217 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
4218 parallel_devices[i][0] = '\0';
4219 parallel_device_index = 0;
4221 usb_devices_index = 0;
4226 /* default mac address of the first network interface */
4234 hd_filename[0] = argv[optind++];
4236 const QEMUOption *popt;
4239 popt = qemu_options;
4242 fprintf(stderr, "%s: invalid option -- '%s'\n",
4246 if (!strcmp(popt->name, r + 1))
4250 if (popt->flags & HAS_ARG) {
4251 if (optind >= argc) {
4252 fprintf(stderr, "%s: option '%s' requires an argument\n",
4256 optarg = argv[optind++];
4261 switch(popt->index) {
4263 machine = find_machine(optarg);
4266 printf("Supported machines are:\n");
4267 for(m = first_machine; m != NULL; m = m->next) {
4268 printf("%-10s %s%s\n",
4270 m == first_machine ? " (default)" : "");
4275 case QEMU_OPTION_initrd:
4276 initrd_filename = optarg;
4278 case QEMU_OPTION_hda:
4279 case QEMU_OPTION_hdb:
4280 case QEMU_OPTION_hdc:
4281 case QEMU_OPTION_hdd:
4284 hd_index = popt->index - QEMU_OPTION_hda;
4285 hd_filename[hd_index] = optarg;
4286 if (hd_index == cdrom_index)
4290 case QEMU_OPTION_snapshot:
4293 case QEMU_OPTION_hdachs:
4297 cyls = strtol(p, (char **)&p, 0);
4298 if (cyls < 1 || cyls > 16383)
4303 heads = strtol(p, (char **)&p, 0);
4304 if (heads < 1 || heads > 16)
4309 secs = strtol(p, (char **)&p, 0);
4310 if (secs < 1 || secs > 63)
4314 if (!strcmp(p, "none"))
4315 translation = BIOS_ATA_TRANSLATION_NONE;
4316 else if (!strcmp(p, "lba"))
4317 translation = BIOS_ATA_TRANSLATION_LBA;
4318 else if (!strcmp(p, "auto"))
4319 translation = BIOS_ATA_TRANSLATION_AUTO;
4322 } else if (*p != '\0') {
4324 fprintf(stderr, "qemu: invalid physical CHS format\n");
4329 case QEMU_OPTION_nographic:
4330 pstrcpy(monitor_device, sizeof(monitor_device), "stdio");
4331 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "stdio");
4334 case QEMU_OPTION_kernel:
4335 kernel_filename = optarg;
4337 case QEMU_OPTION_append:
4338 kernel_cmdline = optarg;
4340 case QEMU_OPTION_cdrom:
4341 if (cdrom_index >= 0) {
4342 hd_filename[cdrom_index] = optarg;
4345 case QEMU_OPTION_boot:
4346 boot_device = optarg[0];
4347 if (boot_device != 'a' &&
4350 boot_device != 'n' &&
4352 boot_device != 'c' && boot_device != 'd') {
4353 fprintf(stderr, "qemu: invalid boot device '%c'\n", boot_device);
4357 case QEMU_OPTION_fda:
4358 fd_filename[0] = optarg;
4360 case QEMU_OPTION_fdb:
4361 fd_filename[1] = optarg;
4363 case QEMU_OPTION_no_code_copy:
4364 code_copy_enabled = 0;
4366 case QEMU_OPTION_net:
4367 if (nb_net_clients >= MAX_NET_CLIENTS) {
4368 fprintf(stderr, "qemu: too many network clients\n");
4371 pstrcpy(net_clients[nb_net_clients],
4372 sizeof(net_clients[0]),
4377 case QEMU_OPTION_tftp:
4378 tftp_prefix = optarg;
4381 case QEMU_OPTION_smb:
4382 net_slirp_smb(optarg);
4385 case QEMU_OPTION_redir:
4386 net_slirp_redir(optarg);
4390 case QEMU_OPTION_enable_audio:
4397 case QEMU_OPTION_audio_help:
4401 case QEMU_OPTION_soundhw:
4402 select_soundhw (optarg);
4409 ram_size = atoi(optarg) * 1024 * 1024;
4412 if (ram_size > PHYS_RAM_MAX_SIZE) {
4413 fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
4414 PHYS_RAM_MAX_SIZE / (1024 * 1024));
4423 mask = cpu_str_to_log_mask(optarg);
4425 printf("Log items (comma separated):\n");
4426 for(item = cpu_log_items; item->mask != 0; item++) {
4427 printf("%-10s %s\n", item->name, item->help);
4434 #ifdef CONFIG_GDBSTUB
4439 gdbstub_port = atoi(optarg);
4446 start_emulation = 0;
4449 keyboard_layout = optarg;
4451 case QEMU_OPTION_localtime:
4454 case QEMU_OPTION_cirrusvga:
4455 cirrus_vga_enabled = 1;
4457 case QEMU_OPTION_std_vga:
4458 cirrus_vga_enabled = 0;
4465 w = strtol(p, (char **)&p, 10);
4468 fprintf(stderr, "qemu: invalid resolution or depth\n");
4474 h = strtol(p, (char **)&p, 10);
4479 depth = strtol(p, (char **)&p, 10);
4480 if (depth != 8 && depth != 15 && depth != 16 &&
4481 depth != 24 && depth != 32)
4483 } else if (*p == '\0') {
4484 depth = graphic_depth;
4491 graphic_depth = depth;
4494 case QEMU_OPTION_monitor:
4495 pstrcpy(monitor_device, sizeof(monitor_device), optarg);
4497 case QEMU_OPTION_serial:
4498 if (serial_device_index >= MAX_SERIAL_PORTS) {
4499 fprintf(stderr, "qemu: too many serial ports\n");
4502 pstrcpy(serial_devices[serial_device_index],
4503 sizeof(serial_devices[0]), optarg);
4504 serial_device_index++;
4506 case QEMU_OPTION_parallel:
4507 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
4508 fprintf(stderr, "qemu: too many parallel ports\n");
4511 pstrcpy(parallel_devices[parallel_device_index],
4512 sizeof(parallel_devices[0]), optarg);
4513 parallel_device_index++;
4515 case QEMU_OPTION_loadvm:
4518 case QEMU_OPTION_full_screen:
4521 case QEMU_OPTION_pidfile:
4522 create_pidfile(optarg);
4525 case QEMU_OPTION_win2k_hack:
4526 win2k_install_hack = 1;
4530 case QEMU_OPTION_no_kqemu:
4534 case QEMU_OPTION_usb:
4537 case QEMU_OPTION_usbdevice:
4539 if (usb_devices_index >= MAX_VM_USB_PORTS) {
4540 fprintf(stderr, "Too many USB devices\n");
4543 pstrcpy(usb_devices[usb_devices_index],
4544 sizeof(usb_devices[usb_devices_index]),
4546 usb_devices_index++;
4548 case QEMU_OPTION_smp:
4549 smp_cpus = atoi(optarg);
4550 if (smp_cpus < 1 || smp_cpus > 8) {
4551 fprintf(stderr, "Invalid number of CPUs\n");
4559 linux_boot = (kernel_filename != NULL);
4562 hd_filename[0] == '\0' &&
4563 (cdrom_index >= 0 && hd_filename[cdrom_index] == '\0') &&
4564 fd_filename[0] == '\0')
4567 /* boot to cd by default if no hard disk */
4568 if (hd_filename[0] == '\0' && boot_device == 'c') {
4569 if (fd_filename[0] != '\0')
4575 #if !defined(CONFIG_SOFTMMU)
4576 /* must avoid mmap() usage of glibc by setting a buffer "by hand" */
4578 static uint8_t stdout_buf[4096];
4579 setvbuf(stdout, stdout_buf, _IOLBF, sizeof(stdout_buf));
4582 setvbuf(stdout, NULL, _IOLBF, 0);
4585 /* init network clients */
4586 if (nb_net_clients == 0) {
4587 /* if no clients, we use a default config */
4588 pstrcpy(net_clients[0], sizeof(net_clients[0]),
4590 pstrcpy(net_clients[1], sizeof(net_clients[0]),
4595 for(i = 0;i < nb_net_clients; i++) {
4596 if (net_client_init(net_clients[i]) < 0)
4600 /* init the memory */
4601 phys_ram_size = ram_size + vga_ram_size + bios_size;
4603 #ifdef CONFIG_SOFTMMU
4604 phys_ram_base = qemu_vmalloc(phys_ram_size);
4605 if (!phys_ram_base) {
4606 fprintf(stderr, "Could not allocate physical memory\n");
4610 /* as we must map the same page at several addresses, we must use
4615 tmpdir = getenv("QEMU_TMPDIR");
4618 snprintf(phys_ram_file, sizeof(phys_ram_file), "%s/vlXXXXXX", tmpdir);
4619 if (mkstemp(phys_ram_file) < 0) {
4620 fprintf(stderr, "Could not create temporary memory file '%s'\n",
4624 phys_ram_fd = open(phys_ram_file, O_CREAT | O_TRUNC | O_RDWR, 0600);
4625 if (phys_ram_fd < 0) {
4626 fprintf(stderr, "Could not open temporary memory file '%s'\n",
4630 ftruncate(phys_ram_fd, phys_ram_size);
4631 unlink(phys_ram_file);
4632 phys_ram_base = mmap(get_mmap_addr(phys_ram_size),
4634 PROT_WRITE | PROT_READ, MAP_SHARED | MAP_FIXED,
4636 if (phys_ram_base == MAP_FAILED) {
4637 fprintf(stderr, "Could not map physical memory\n");
4643 /* we always create the cdrom drive, even if no disk is there */
4645 if (cdrom_index >= 0) {
4646 bs_table[cdrom_index] = bdrv_new("cdrom");
4647 bdrv_set_type_hint(bs_table[cdrom_index], BDRV_TYPE_CDROM);
4650 /* open the virtual block devices */
4651 for(i = 0; i < MAX_DISKS; i++) {
4652 if (hd_filename[i]) {
4655 snprintf(buf, sizeof(buf), "hd%c", i + 'a');
4656 bs_table[i] = bdrv_new(buf);
4658 if (bdrv_open(bs_table[i], hd_filename[i], snapshot) < 0) {
4659 fprintf(stderr, "qemu: could not open hard disk image '%s'\n",
4663 if (i == 0 && cyls != 0) {
4664 bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
4665 bdrv_set_translation_hint(bs_table[i], translation);
4670 /* we always create at least one floppy disk */
4671 fd_table[0] = bdrv_new("fda");
4672 bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
4674 for(i = 0; i < MAX_FD; i++) {
4675 if (fd_filename[i]) {
4678 snprintf(buf, sizeof(buf), "fd%c", i + 'a');
4679 fd_table[i] = bdrv_new(buf);
4680 bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
4682 if (fd_filename[i] != '\0') {
4683 if (bdrv_open(fd_table[i], fd_filename[i], snapshot) < 0) {
4684 fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
4692 /* init USB devices */
4694 vm_usb_hub = usb_hub_init(vm_usb_ports, MAX_VM_USB_PORTS);
4695 for(i = 0; i < usb_devices_index; i++) {
4696 if (usb_device_add(usb_devices[i]) < 0) {
4697 fprintf(stderr, "Warning: could not add USB device %s\n",
4703 register_savevm("timer", 0, 1, timer_save, timer_load, NULL);
4704 register_savevm("ram", 0, 1, ram_save, ram_load, NULL);
4707 cpu_calibrate_ticks();
4711 dumb_display_init(ds);
4713 #if defined(CONFIG_SDL)
4714 sdl_display_init(ds, full_screen);
4715 #elif defined(CONFIG_COCOA)
4716 cocoa_display_init(ds, full_screen);
4718 dumb_display_init(ds);
4722 vga_console = graphic_console_init(ds);
4724 monitor_hd = qemu_chr_open(monitor_device);
4726 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
4729 monitor_init(monitor_hd, !nographic);
4731 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
4732 if (serial_devices[i][0] != '\0') {
4733 serial_hds[i] = qemu_chr_open(serial_devices[i]);
4734 if (!serial_hds[i]) {
4735 fprintf(stderr, "qemu: could not open serial device '%s'\n",
4739 if (!strcmp(serial_devices[i], "vc"))
4740 qemu_chr_printf(serial_hds[i], "serial%d console\n", i);
4744 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
4745 if (parallel_devices[i][0] != '\0') {
4746 parallel_hds[i] = qemu_chr_open(parallel_devices[i]);
4747 if (!parallel_hds[i]) {
4748 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
4749 parallel_devices[i]);
4752 if (!strcmp(parallel_devices[i], "vc"))
4753 qemu_chr_printf(parallel_hds[i], "parallel%d console\n", i);
4757 /* setup cpu signal handlers for MMU / self modifying code handling */
4758 #if !defined(CONFIG_SOFTMMU)
4760 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
4763 signal_stack = memalign(16, SIGNAL_STACK_SIZE);
4764 stk.ss_sp = signal_stack;
4765 stk.ss_size = SIGNAL_STACK_SIZE;
4768 if (sigaltstack(&stk, NULL) < 0) {
4769 perror("sigaltstack");
4775 struct sigaction act;
4777 sigfillset(&act.sa_mask);
4778 act.sa_flags = SA_SIGINFO;
4779 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
4780 act.sa_flags |= SA_ONSTACK;
4782 act.sa_sigaction = host_segv_handler;
4783 sigaction(SIGSEGV, &act, NULL);
4784 sigaction(SIGBUS, &act, NULL);
4785 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
4786 sigaction(SIGFPE, &act, NULL);
4793 struct sigaction act;
4794 sigfillset(&act.sa_mask);
4796 act.sa_handler = SIG_IGN;
4797 sigaction(SIGPIPE, &act, NULL);
4802 machine->init(ram_size, vga_ram_size, boot_device,
4803 ds, fd_filename, snapshot,
4804 kernel_filename, kernel_cmdline, initrd_filename);
4806 gui_timer = qemu_new_timer(rt_clock, gui_update, NULL);
4807 qemu_mod_timer(gui_timer, qemu_get_clock(rt_clock));
4809 #ifdef CONFIG_GDBSTUB
4811 if (gdbserver_start(gdbstub_port) < 0) {
4812 fprintf(stderr, "Could not open gdbserver socket on port %d\n",
4816 printf("Waiting gdb connection on port %d\n", gdbstub_port);
4821 qemu_loadvm(loadvm);
4824 /* XXX: simplify init */
4826 if (start_emulation) {