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 */
88 #define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
90 //#define DEBUG_UNUSED_IOPORT
91 //#define DEBUG_IOPORT
93 #if !defined(CONFIG_SOFTMMU)
94 #define PHYS_RAM_MAX_SIZE (256 * 1024 * 1024)
96 #define PHYS_RAM_MAX_SIZE (2047 * 1024 * 1024)
100 #define DEFAULT_RAM_SIZE 144
102 #define DEFAULT_RAM_SIZE 128
105 #define GUI_REFRESH_INTERVAL 30
107 /* XXX: use a two level table to limit memory usage */
108 #define MAX_IOPORTS 65536
110 const char *bios_dir = CONFIG_QEMU_SHAREDIR;
111 char phys_ram_file[1024];
112 CPUState *global_env;
113 CPUState *cpu_single_env;
114 void *ioport_opaque[MAX_IOPORTS];
115 IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
116 IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
117 BlockDriverState *bs_table[MAX_DISKS], *fd_table[MAX_FD];
120 static DisplayState display_state;
122 const char* keyboard_layout = NULL;
123 int64_t ticks_per_sec;
124 int boot_device = 'c';
126 int pit_min_timer_count = 0;
128 NICInfo nd_table[MAX_NICS];
129 QEMUTimer *gui_timer;
132 int audio_enabled = 0;
133 int sb16_enabled = 0;
134 int adlib_enabled = 0;
136 int es1370_enabled = 0;
139 int cirrus_vga_enabled = 1;
141 int graphic_width = 1024;
142 int graphic_height = 768;
144 int graphic_width = 800;
145 int graphic_height = 600;
147 int graphic_depth = 15;
149 TextConsole *vga_console;
150 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
151 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
153 int win2k_install_hack = 0;
156 USBPort *vm_usb_ports[MAX_VM_USB_PORTS];
157 USBDevice *vm_usb_hub;
158 static VLANState *first_vlan;
160 /***********************************************************/
161 /* x86 ISA bus support */
163 target_phys_addr_t isa_mem_base = 0;
166 uint32_t default_ioport_readb(void *opaque, uint32_t address)
168 #ifdef DEBUG_UNUSED_IOPORT
169 fprintf(stderr, "inb: port=0x%04x\n", address);
174 void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
176 #ifdef DEBUG_UNUSED_IOPORT
177 fprintf(stderr, "outb: port=0x%04x data=0x%02x\n", address, data);
181 /* default is to make two byte accesses */
182 uint32_t default_ioport_readw(void *opaque, uint32_t address)
185 data = ioport_read_table[0][address](ioport_opaque[address], address);
186 address = (address + 1) & (MAX_IOPORTS - 1);
187 data |= ioport_read_table[0][address](ioport_opaque[address], address) << 8;
191 void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
193 ioport_write_table[0][address](ioport_opaque[address], address, data & 0xff);
194 address = (address + 1) & (MAX_IOPORTS - 1);
195 ioport_write_table[0][address](ioport_opaque[address], address, (data >> 8) & 0xff);
198 uint32_t default_ioport_readl(void *opaque, uint32_t address)
200 #ifdef DEBUG_UNUSED_IOPORT
201 fprintf(stderr, "inl: port=0x%04x\n", address);
206 void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
208 #ifdef DEBUG_UNUSED_IOPORT
209 fprintf(stderr, "outl: port=0x%04x data=0x%02x\n", address, data);
213 void init_ioports(void)
217 for(i = 0; i < MAX_IOPORTS; i++) {
218 ioport_read_table[0][i] = default_ioport_readb;
219 ioport_write_table[0][i] = default_ioport_writeb;
220 ioport_read_table[1][i] = default_ioport_readw;
221 ioport_write_table[1][i] = default_ioport_writew;
222 ioport_read_table[2][i] = default_ioport_readl;
223 ioport_write_table[2][i] = default_ioport_writel;
227 /* size is the word size in byte */
228 int register_ioport_read(int start, int length, int size,
229 IOPortReadFunc *func, void *opaque)
235 } else if (size == 2) {
237 } else if (size == 4) {
240 hw_error("register_ioport_read: invalid size");
243 for(i = start; i < start + length; i += size) {
244 ioport_read_table[bsize][i] = func;
245 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
246 hw_error("register_ioport_read: invalid opaque");
247 ioport_opaque[i] = opaque;
252 /* size is the word size in byte */
253 int register_ioport_write(int start, int length, int size,
254 IOPortWriteFunc *func, void *opaque)
260 } else if (size == 2) {
262 } else if (size == 4) {
265 hw_error("register_ioport_write: invalid size");
268 for(i = start; i < start + length; i += size) {
269 ioport_write_table[bsize][i] = func;
270 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
271 hw_error("register_ioport_read: invalid opaque");
272 ioport_opaque[i] = opaque;
277 void isa_unassign_ioport(int start, int length)
281 for(i = start; i < start + length; i++) {
282 ioport_read_table[0][i] = default_ioport_readb;
283 ioport_read_table[1][i] = default_ioport_readw;
284 ioport_read_table[2][i] = default_ioport_readl;
286 ioport_write_table[0][i] = default_ioport_writeb;
287 ioport_write_table[1][i] = default_ioport_writew;
288 ioport_write_table[2][i] = default_ioport_writel;
292 /***********************************************************/
294 void pstrcpy(char *buf, int buf_size, const char *str)
304 if (c == 0 || q >= buf + buf_size - 1)
311 /* strcat and truncate. */
312 char *pstrcat(char *buf, int buf_size, const char *s)
317 pstrcpy(buf + len, buf_size - len, s);
321 int strstart(const char *str, const char *val, const char **ptr)
337 /* return the size or -1 if error */
338 int get_image_size(const char *filename)
341 fd = open(filename, O_RDONLY | O_BINARY);
344 size = lseek(fd, 0, SEEK_END);
349 /* return the size or -1 if error */
350 int load_image(const char *filename, uint8_t *addr)
353 fd = open(filename, O_RDONLY | O_BINARY);
356 size = lseek(fd, 0, SEEK_END);
357 lseek(fd, 0, SEEK_SET);
358 if (read(fd, addr, size) != size) {
366 void cpu_outb(CPUState *env, int addr, int val)
369 if (loglevel & CPU_LOG_IOPORT)
370 fprintf(logfile, "outb: %04x %02x\n", addr, val);
372 ioport_write_table[0][addr](ioport_opaque[addr], addr, val);
375 void cpu_outw(CPUState *env, int addr, int val)
378 if (loglevel & CPU_LOG_IOPORT)
379 fprintf(logfile, "outw: %04x %04x\n", addr, val);
381 ioport_write_table[1][addr](ioport_opaque[addr], addr, val);
384 void cpu_outl(CPUState *env, int addr, int val)
387 if (loglevel & CPU_LOG_IOPORT)
388 fprintf(logfile, "outl: %04x %08x\n", addr, val);
390 ioport_write_table[2][addr](ioport_opaque[addr], addr, val);
393 int cpu_inb(CPUState *env, int addr)
396 val = ioport_read_table[0][addr](ioport_opaque[addr], addr);
398 if (loglevel & CPU_LOG_IOPORT)
399 fprintf(logfile, "inb : %04x %02x\n", addr, val);
404 int cpu_inw(CPUState *env, int addr)
407 val = ioport_read_table[1][addr](ioport_opaque[addr], addr);
409 if (loglevel & CPU_LOG_IOPORT)
410 fprintf(logfile, "inw : %04x %04x\n", addr, val);
415 int cpu_inl(CPUState *env, int addr)
418 val = ioport_read_table[2][addr](ioport_opaque[addr], addr);
420 if (loglevel & CPU_LOG_IOPORT)
421 fprintf(logfile, "inl : %04x %08x\n", addr, val);
426 /***********************************************************/
427 void hw_error(const char *fmt, ...)
432 fprintf(stderr, "qemu: hardware error: ");
433 vfprintf(stderr, fmt, ap);
434 fprintf(stderr, "\n");
436 cpu_dump_state(global_env, stderr, fprintf, X86_DUMP_FPU | X86_DUMP_CCOP);
438 cpu_dump_state(global_env, stderr, fprintf, 0);
444 /***********************************************************/
447 static QEMUPutKBDEvent *qemu_put_kbd_event;
448 static void *qemu_put_kbd_event_opaque;
449 static QEMUPutMouseEvent *qemu_put_mouse_event;
450 static void *qemu_put_mouse_event_opaque;
452 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
454 qemu_put_kbd_event_opaque = opaque;
455 qemu_put_kbd_event = func;
458 void qemu_add_mouse_event_handler(QEMUPutMouseEvent *func, void *opaque)
460 qemu_put_mouse_event_opaque = opaque;
461 qemu_put_mouse_event = func;
464 void kbd_put_keycode(int keycode)
466 if (qemu_put_kbd_event) {
467 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
471 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
473 if (qemu_put_mouse_event) {
474 qemu_put_mouse_event(qemu_put_mouse_event_opaque,
475 dx, dy, dz, buttons_state);
479 /***********************************************************/
482 #if defined(__powerpc__)
484 static inline uint32_t get_tbl(void)
487 asm volatile("mftb %0" : "=r" (tbl));
491 static inline uint32_t get_tbu(void)
494 asm volatile("mftbu %0" : "=r" (tbl));
498 int64_t cpu_get_real_ticks(void)
501 /* NOTE: we test if wrapping has occurred */
507 return ((int64_t)h << 32) | l;
510 #elif defined(__i386__)
512 int64_t cpu_get_real_ticks(void)
515 asm volatile ("rdtsc" : "=A" (val));
519 #elif defined(__x86_64__)
521 int64_t cpu_get_real_ticks(void)
525 asm volatile("rdtsc" : "=a" (low), "=d" (high));
532 #elif defined(__ia64)
534 int64_t cpu_get_real_ticks(void)
537 asm volatile ("mov %0 = ar.itc" : "=r"(val) :: "memory");
541 #elif defined(__s390__)
543 int64_t cpu_get_real_ticks(void)
546 asm volatile("stck 0(%1)" : "=m" (val) : "a" (&val) : "cc");
551 #error unsupported CPU
554 static int64_t cpu_ticks_offset;
555 static int cpu_ticks_enabled;
557 static inline int64_t cpu_get_ticks(void)
559 if (!cpu_ticks_enabled) {
560 return cpu_ticks_offset;
562 return cpu_get_real_ticks() + cpu_ticks_offset;
566 /* enable cpu_get_ticks() */
567 void cpu_enable_ticks(void)
569 if (!cpu_ticks_enabled) {
570 cpu_ticks_offset -= cpu_get_real_ticks();
571 cpu_ticks_enabled = 1;
575 /* disable cpu_get_ticks() : the clock is stopped. You must not call
576 cpu_get_ticks() after that. */
577 void cpu_disable_ticks(void)
579 if (cpu_ticks_enabled) {
580 cpu_ticks_offset = cpu_get_ticks();
581 cpu_ticks_enabled = 0;
585 static int64_t get_clock(void)
590 return ((int64_t)tb.time * 1000 + (int64_t)tb.millitm) * 1000;
593 gettimeofday(&tv, NULL);
594 return tv.tv_sec * 1000000LL + tv.tv_usec;
598 void cpu_calibrate_ticks(void)
603 ticks = cpu_get_real_ticks();
609 usec = get_clock() - usec;
610 ticks = cpu_get_real_ticks() - ticks;
611 ticks_per_sec = (ticks * 1000000LL + (usec >> 1)) / usec;
614 /* compute with 96 bit intermediate result: (a*b)/c */
615 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
620 #ifdef WORDS_BIGENDIAN
630 rl = (uint64_t)u.l.low * (uint64_t)b;
631 rh = (uint64_t)u.l.high * (uint64_t)b;
634 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
638 #define QEMU_TIMER_REALTIME 0
639 #define QEMU_TIMER_VIRTUAL 1
643 /* XXX: add frequency */
651 struct QEMUTimer *next;
657 static QEMUTimer *active_timers[2];
659 static MMRESULT timerID;
661 /* frequency of the times() clock tick */
662 static int timer_freq;
665 QEMUClock *qemu_new_clock(int type)
668 clock = qemu_mallocz(sizeof(QEMUClock));
675 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
679 ts = qemu_mallocz(sizeof(QEMUTimer));
686 void qemu_free_timer(QEMUTimer *ts)
691 /* stop a timer, but do not dealloc it */
692 void qemu_del_timer(QEMUTimer *ts)
696 /* NOTE: this code must be signal safe because
697 qemu_timer_expired() can be called from a signal. */
698 pt = &active_timers[ts->clock->type];
711 /* modify the current timer so that it will be fired when current_time
712 >= expire_time. The corresponding callback will be called. */
713 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
719 /* add the timer in the sorted list */
720 /* NOTE: this code must be signal safe because
721 qemu_timer_expired() can be called from a signal. */
722 pt = &active_timers[ts->clock->type];
727 if (t->expire_time > expire_time)
731 ts->expire_time = expire_time;
736 int qemu_timer_pending(QEMUTimer *ts)
739 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
746 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
750 return (timer_head->expire_time <= current_time);
753 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
759 if (!ts || ts->expire_time > current_time)
761 /* remove timer from the list before calling the callback */
762 *ptimer_head = ts->next;
765 /* run the callback (the timer list can be modified) */
770 int64_t qemu_get_clock(QEMUClock *clock)
772 switch(clock->type) {
773 case QEMU_TIMER_REALTIME:
775 return GetTickCount();
780 /* Note that using gettimeofday() is not a good solution
781 for timers because its value change when the date is
783 if (timer_freq == 100) {
784 return times(&tp) * 10;
786 return ((int64_t)times(&tp) * 1000) / timer_freq;
791 case QEMU_TIMER_VIRTUAL:
792 return cpu_get_ticks();
797 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
799 uint64_t expire_time;
801 if (qemu_timer_pending(ts)) {
802 expire_time = ts->expire_time;
806 qemu_put_be64(f, expire_time);
809 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
811 uint64_t expire_time;
813 expire_time = qemu_get_be64(f);
814 if (expire_time != -1) {
815 qemu_mod_timer(ts, expire_time);
821 static void timer_save(QEMUFile *f, void *opaque)
823 if (cpu_ticks_enabled) {
824 hw_error("cannot save state if virtual timers are running");
826 qemu_put_be64s(f, &cpu_ticks_offset);
827 qemu_put_be64s(f, &ticks_per_sec);
830 static int timer_load(QEMUFile *f, void *opaque, int version_id)
834 if (cpu_ticks_enabled) {
837 qemu_get_be64s(f, &cpu_ticks_offset);
838 qemu_get_be64s(f, &ticks_per_sec);
843 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
844 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
846 static void host_alarm_handler(int host_signum)
850 #define DISP_FREQ 1000
852 static int64_t delta_min = INT64_MAX;
853 static int64_t delta_max, delta_cum, last_clock, delta, ti;
855 ti = qemu_get_clock(vm_clock);
856 if (last_clock != 0) {
857 delta = ti - last_clock;
858 if (delta < delta_min)
860 if (delta > delta_max)
863 if (++count == DISP_FREQ) {
864 printf("timer: min=%lld us max=%lld us avg=%lld us avg_freq=%0.3f Hz\n",
865 muldiv64(delta_min, 1000000, ticks_per_sec),
866 muldiv64(delta_max, 1000000, ticks_per_sec),
867 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
868 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
870 delta_min = INT64_MAX;
878 if (qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
879 qemu_get_clock(vm_clock)) ||
880 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
881 qemu_get_clock(rt_clock))) {
882 /* stop the cpu because a timer occured */
883 cpu_interrupt(global_env, CPU_INTERRUPT_EXIT);
885 if (global_env->kqemu_enabled) {
886 kqemu_cpu_interrupt(global_env);
894 #if defined(__linux__)
896 #define RTC_FREQ 1024
900 static int start_rtc_timer(void)
902 rtc_fd = open("/dev/rtc", O_RDONLY);
905 if (ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
906 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
907 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
908 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
911 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
916 pit_min_timer_count = PIT_FREQ / RTC_FREQ;
922 static int start_rtc_timer(void)
927 #endif /* !defined(__linux__) */
929 #endif /* !defined(_WIN32) */
931 static void init_timers(void)
933 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
934 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
939 timerID = timeSetEvent(1, // interval (ms)
941 host_alarm_handler, // function
942 (DWORD)&count, // user parameter
943 TIME_PERIODIC | TIME_CALLBACK_FUNCTION);
945 perror("failed timer alarm");
949 pit_min_timer_count = ((uint64_t)10000 * PIT_FREQ) / 1000000;
952 struct sigaction act;
953 struct itimerval itv;
955 /* get times() syscall frequency */
956 timer_freq = sysconf(_SC_CLK_TCK);
959 sigfillset(&act.sa_mask);
961 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
962 act.sa_flags |= SA_ONSTACK;
964 act.sa_handler = host_alarm_handler;
965 sigaction(SIGALRM, &act, NULL);
967 itv.it_interval.tv_sec = 0;
968 itv.it_interval.tv_usec = 999; /* for i386 kernel 2.6 to get 1 ms */
969 itv.it_value.tv_sec = 0;
970 itv.it_value.tv_usec = 10 * 1000;
971 setitimer(ITIMER_REAL, &itv, NULL);
972 /* we probe the tick duration of the kernel to inform the user if
973 the emulated kernel requested a too high timer frequency */
974 getitimer(ITIMER_REAL, &itv);
976 #if defined(__linux__)
977 if (itv.it_interval.tv_usec > 1000) {
978 /* try to use /dev/rtc to have a faster timer */
979 if (start_rtc_timer() < 0)
982 itv.it_interval.tv_sec = 0;
983 itv.it_interval.tv_usec = 0;
984 itv.it_value.tv_sec = 0;
985 itv.it_value.tv_usec = 0;
986 setitimer(ITIMER_REAL, &itv, NULL);
989 sigaction(SIGIO, &act, NULL);
990 fcntl(rtc_fd, F_SETFL, O_ASYNC);
991 fcntl(rtc_fd, F_SETOWN, getpid());
993 #endif /* defined(__linux__) */
996 pit_min_timer_count = ((uint64_t)itv.it_interval.tv_usec *
1003 void quit_timers(void)
1006 timeKillEvent(timerID);
1010 /***********************************************************/
1011 /* character device */
1013 int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1015 return s->chr_write(s, buf, len);
1018 int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1022 return s->chr_ioctl(s, cmd, arg);
1025 void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1030 vsnprintf(buf, sizeof(buf), fmt, ap);
1031 qemu_chr_write(s, buf, strlen(buf));
1035 void qemu_chr_send_event(CharDriverState *s, int event)
1037 if (s->chr_send_event)
1038 s->chr_send_event(s, event);
1041 void qemu_chr_add_read_handler(CharDriverState *s,
1042 IOCanRWHandler *fd_can_read,
1043 IOReadHandler *fd_read, void *opaque)
1045 s->chr_add_read_handler(s, fd_can_read, fd_read, opaque);
1048 void qemu_chr_add_event_handler(CharDriverState *s, IOEventHandler *chr_event)
1050 s->chr_event = chr_event;
1053 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1058 static void null_chr_add_read_handler(CharDriverState *chr,
1059 IOCanRWHandler *fd_can_read,
1060 IOReadHandler *fd_read, void *opaque)
1064 CharDriverState *qemu_chr_open_null(void)
1066 CharDriverState *chr;
1068 chr = qemu_mallocz(sizeof(CharDriverState));
1071 chr->chr_write = null_chr_write;
1072 chr->chr_add_read_handler = null_chr_add_read_handler;
1080 IOCanRWHandler *fd_can_read;
1081 IOReadHandler *fd_read;
1086 #define STDIO_MAX_CLIENTS 2
1088 static int stdio_nb_clients;
1089 static CharDriverState *stdio_clients[STDIO_MAX_CLIENTS];
1091 static int unix_write(int fd, const uint8_t *buf, int len1)
1097 ret = write(fd, buf, len);
1099 if (errno != EINTR && errno != EAGAIN)
1101 } else if (ret == 0) {
1111 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1113 FDCharDriver *s = chr->opaque;
1114 return unix_write(s->fd_out, buf, len);
1117 static int fd_chr_read_poll(void *opaque)
1119 CharDriverState *chr = opaque;
1120 FDCharDriver *s = chr->opaque;
1122 s->max_size = s->fd_can_read(s->fd_opaque);
1126 static void fd_chr_read(void *opaque)
1128 CharDriverState *chr = opaque;
1129 FDCharDriver *s = chr->opaque;
1134 if (len > s->max_size)
1138 size = read(s->fd_in, buf, len);
1140 s->fd_read(s->fd_opaque, buf, size);
1144 static void fd_chr_add_read_handler(CharDriverState *chr,
1145 IOCanRWHandler *fd_can_read,
1146 IOReadHandler *fd_read, void *opaque)
1148 FDCharDriver *s = chr->opaque;
1150 if (s->fd_in >= 0) {
1151 s->fd_can_read = fd_can_read;
1152 s->fd_read = fd_read;
1153 s->fd_opaque = opaque;
1154 if (nographic && s->fd_in == 0) {
1156 qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
1157 fd_chr_read, NULL, chr);
1162 /* open a character device to a unix fd */
1163 CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
1165 CharDriverState *chr;
1168 chr = qemu_mallocz(sizeof(CharDriverState));
1171 s = qemu_mallocz(sizeof(FDCharDriver));
1179 chr->chr_write = fd_chr_write;
1180 chr->chr_add_read_handler = fd_chr_add_read_handler;
1184 CharDriverState *qemu_chr_open_file_out(const char *file_out)
1188 fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY);
1191 return qemu_chr_open_fd(-1, fd_out);
1194 CharDriverState *qemu_chr_open_pipe(const char *filename)
1198 fd = open(filename, O_RDWR | O_BINARY);
1201 return qemu_chr_open_fd(fd, fd);
1205 /* for STDIO, we handle the case where several clients use it
1208 #define TERM_ESCAPE 0x01 /* ctrl-a is used for escape */
1210 #define TERM_FIFO_MAX_SIZE 1
1212 static int term_got_escape, client_index;
1213 static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
1216 void term_print_help(void)
1219 "C-a h print this help\n"
1220 "C-a x exit emulator\n"
1221 "C-a s save disk data back to file (if -snapshot)\n"
1222 "C-a b send break (magic sysrq)\n"
1223 "C-a c switch between console and monitor\n"
1224 "C-a C-a send C-a\n"
1228 /* called when a char is received */
1229 static void stdio_received_byte(int ch)
1231 if (term_got_escape) {
1232 term_got_escape = 0;
1243 for (i = 0; i < MAX_DISKS; i++) {
1245 bdrv_commit(bs_table[i]);
1250 if (client_index < stdio_nb_clients) {
1251 CharDriverState *chr;
1254 chr = stdio_clients[client_index];
1256 chr->chr_event(s->fd_opaque, CHR_EVENT_BREAK);
1261 if (client_index >= stdio_nb_clients)
1263 if (client_index == 0) {
1264 /* send a new line in the monitor to get the prompt */
1272 } else if (ch == TERM_ESCAPE) {
1273 term_got_escape = 1;
1276 if (client_index < stdio_nb_clients) {
1278 CharDriverState *chr;
1281 chr = stdio_clients[client_index];
1283 if (s->fd_can_read(s->fd_opaque) > 0) {
1285 s->fd_read(s->fd_opaque, buf, 1);
1286 } else if (term_fifo_size == 0) {
1287 term_fifo[term_fifo_size++] = ch;
1293 static int stdio_read_poll(void *opaque)
1295 CharDriverState *chr;
1298 if (client_index < stdio_nb_clients) {
1299 chr = stdio_clients[client_index];
1301 /* try to flush the queue if needed */
1302 if (term_fifo_size != 0 && s->fd_can_read(s->fd_opaque) > 0) {
1303 s->fd_read(s->fd_opaque, term_fifo, 1);
1306 /* see if we can absorb more chars */
1307 if (term_fifo_size == 0)
1316 static void stdio_read(void *opaque)
1321 size = read(0, buf, 1);
1323 stdio_received_byte(buf[0]);
1326 /* init terminal so that we can grab keys */
1327 static struct termios oldtty;
1328 static int old_fd0_flags;
1330 static void term_exit(void)
1332 tcsetattr (0, TCSANOW, &oldtty);
1333 fcntl(0, F_SETFL, old_fd0_flags);
1336 static void term_init(void)
1340 tcgetattr (0, &tty);
1342 old_fd0_flags = fcntl(0, F_GETFL);
1344 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1345 |INLCR|IGNCR|ICRNL|IXON);
1346 tty.c_oflag |= OPOST;
1347 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1348 /* if graphical mode, we allow Ctrl-C handling */
1350 tty.c_lflag &= ~ISIG;
1351 tty.c_cflag &= ~(CSIZE|PARENB);
1354 tty.c_cc[VTIME] = 0;
1356 tcsetattr (0, TCSANOW, &tty);
1360 fcntl(0, F_SETFL, O_NONBLOCK);
1363 CharDriverState *qemu_chr_open_stdio(void)
1365 CharDriverState *chr;
1368 if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
1370 chr = qemu_chr_open_fd(0, 1);
1371 if (stdio_nb_clients == 0)
1372 qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, NULL);
1373 client_index = stdio_nb_clients;
1375 if (stdio_nb_clients != 0)
1377 chr = qemu_chr_open_fd(0, 1);
1379 stdio_clients[stdio_nb_clients++] = chr;
1380 if (stdio_nb_clients == 1) {
1381 /* set the terminal in raw mode */
1387 #if defined(__linux__)
1388 CharDriverState *qemu_chr_open_pty(void)
1390 char slave_name[1024];
1391 int master_fd, slave_fd;
1393 /* Not satisfying */
1394 if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
1397 fprintf(stderr, "char device redirected to %s\n", slave_name);
1398 return qemu_chr_open_fd(master_fd, master_fd);
1401 static void tty_serial_init(int fd, int speed,
1402 int parity, int data_bits, int stop_bits)
1408 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1409 speed, parity, data_bits, stop_bits);
1411 tcgetattr (fd, &tty);
1453 cfsetispeed(&tty, spd);
1454 cfsetospeed(&tty, spd);
1456 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1457 |INLCR|IGNCR|ICRNL|IXON);
1458 tty.c_oflag |= OPOST;
1459 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1460 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS);
1481 tty.c_cflag |= PARENB;
1484 tty.c_cflag |= PARENB | PARODD;
1488 tcsetattr (fd, TCSANOW, &tty);
1491 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1493 FDCharDriver *s = chr->opaque;
1496 case CHR_IOCTL_SERIAL_SET_PARAMS:
1498 QEMUSerialSetParams *ssp = arg;
1499 tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
1500 ssp->data_bits, ssp->stop_bits);
1503 case CHR_IOCTL_SERIAL_SET_BREAK:
1505 int enable = *(int *)arg;
1507 tcsendbreak(s->fd_in, 1);
1516 CharDriverState *qemu_chr_open_tty(const char *filename)
1518 CharDriverState *chr;
1521 fd = open(filename, O_RDWR | O_NONBLOCK);
1524 fcntl(fd, F_SETFL, O_NONBLOCK);
1525 tty_serial_init(fd, 115200, 'N', 8, 1);
1526 chr = qemu_chr_open_fd(fd, fd);
1529 chr->chr_ioctl = tty_serial_ioctl;
1533 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1535 int fd = (int)chr->opaque;
1539 case CHR_IOCTL_PP_READ_DATA:
1540 if (ioctl(fd, PPRDATA, &b) < 0)
1542 *(uint8_t *)arg = b;
1544 case CHR_IOCTL_PP_WRITE_DATA:
1545 b = *(uint8_t *)arg;
1546 if (ioctl(fd, PPWDATA, &b) < 0)
1549 case CHR_IOCTL_PP_READ_CONTROL:
1550 if (ioctl(fd, PPRCONTROL, &b) < 0)
1552 *(uint8_t *)arg = b;
1554 case CHR_IOCTL_PP_WRITE_CONTROL:
1555 b = *(uint8_t *)arg;
1556 if (ioctl(fd, PPWCONTROL, &b) < 0)
1559 case CHR_IOCTL_PP_READ_STATUS:
1560 if (ioctl(fd, PPRSTATUS, &b) < 0)
1562 *(uint8_t *)arg = b;
1570 CharDriverState *qemu_chr_open_pp(const char *filename)
1572 CharDriverState *chr;
1575 fd = open(filename, O_RDWR);
1579 if (ioctl(fd, PPCLAIM) < 0) {
1584 chr = qemu_mallocz(sizeof(CharDriverState));
1589 chr->opaque = (void *)fd;
1590 chr->chr_write = null_chr_write;
1591 chr->chr_add_read_handler = null_chr_add_read_handler;
1592 chr->chr_ioctl = pp_ioctl;
1597 CharDriverState *qemu_chr_open_pty(void)
1603 #endif /* !defined(_WIN32) */
1605 CharDriverState *qemu_chr_open(const char *filename)
1608 if (!strcmp(filename, "vc")) {
1609 return text_console_init(&display_state);
1610 } else if (!strcmp(filename, "null")) {
1611 return qemu_chr_open_null();
1612 } else if (strstart(filename, "file:", &p)) {
1613 return qemu_chr_open_file_out(p);
1614 } else if (strstart(filename, "pipe:", &p)) {
1615 return qemu_chr_open_pipe(p);
1618 if (!strcmp(filename, "pty")) {
1619 return qemu_chr_open_pty();
1620 } else if (!strcmp(filename, "stdio")) {
1621 return qemu_chr_open_stdio();
1624 #if defined(__linux__)
1625 if (strstart(filename, "/dev/parport", NULL)) {
1626 return qemu_chr_open_pp(filename);
1628 if (strstart(filename, "/dev/", NULL)) {
1629 return qemu_chr_open_tty(filename);
1637 /***********************************************************/
1638 /* network device redirectors */
1640 void hex_dump(FILE *f, const uint8_t *buf, int size)
1644 for(i=0;i<size;i+=16) {
1648 fprintf(f, "%08x ", i);
1651 fprintf(f, " %02x", buf[i+j]);
1656 for(j=0;j<len;j++) {
1658 if (c < ' ' || c > '~')
1660 fprintf(f, "%c", c);
1666 static int parse_macaddr(uint8_t *macaddr, const char *p)
1669 for(i = 0; i < 6; i++) {
1670 macaddr[i] = strtol(p, (char **)&p, 16);
1683 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
1688 p1 = strchr(p, sep);
1694 if (len > buf_size - 1)
1696 memcpy(buf, p, len);
1703 int parse_host_port(struct sockaddr_in *saddr, const char *str)
1711 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
1713 saddr->sin_family = AF_INET;
1714 if (buf[0] == '\0') {
1715 saddr->sin_addr.s_addr = 0;
1717 if (isdigit(buf[0])) {
1718 if (!inet_aton(buf, &saddr->sin_addr))
1724 if ((he = gethostbyname(buf)) == NULL)
1726 saddr->sin_addr = *(struct in_addr *)he->h_addr;
1730 port = strtol(p, (char **)&r, 0);
1733 saddr->sin_port = htons(port);
1737 /* find or alloc a new VLAN */
1738 VLANState *qemu_find_vlan(int id)
1740 VLANState **pvlan, *vlan;
1741 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
1745 vlan = qemu_mallocz(sizeof(VLANState));
1750 pvlan = &first_vlan;
1751 while (*pvlan != NULL)
1752 pvlan = &(*pvlan)->next;
1757 VLANClientState *qemu_new_vlan_client(VLANState *vlan,
1758 IOReadHandler *fd_read, void *opaque)
1760 VLANClientState *vc, **pvc;
1761 vc = qemu_mallocz(sizeof(VLANClientState));
1764 vc->fd_read = fd_read;
1765 vc->opaque = opaque;
1769 pvc = &vlan->first_client;
1770 while (*pvc != NULL)
1771 pvc = &(*pvc)->next;
1776 void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
1778 VLANState *vlan = vc1->vlan;
1779 VLANClientState *vc;
1782 printf("vlan %d send:\n", vlan->id);
1783 hex_dump(stdout, buf, size);
1785 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
1787 vc->fd_read(vc->opaque, buf, size);
1792 #if defined(CONFIG_SLIRP)
1794 /* slirp network adapter */
1796 static int slirp_inited;
1797 static VLANClientState *slirp_vc;
1799 int slirp_can_output(void)
1804 void slirp_output(const uint8_t *pkt, int pkt_len)
1807 printf("slirp output:\n");
1808 hex_dump(stdout, pkt, pkt_len);
1810 qemu_send_packet(slirp_vc, pkt, pkt_len);
1813 static void slirp_receive(void *opaque, const uint8_t *buf, int size)
1816 printf("slirp input:\n");
1817 hex_dump(stdout, buf, size);
1819 slirp_input(buf, size);
1822 static int net_slirp_init(VLANState *vlan)
1824 if (!slirp_inited) {
1828 slirp_vc = qemu_new_vlan_client(vlan,
1829 slirp_receive, NULL);
1830 snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
1834 static void net_slirp_redir(const char *redir_str)
1839 struct in_addr guest_addr;
1840 int host_port, guest_port;
1842 if (!slirp_inited) {
1848 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
1850 if (!strcmp(buf, "tcp")) {
1852 } else if (!strcmp(buf, "udp")) {
1858 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
1860 host_port = strtol(buf, &r, 0);
1864 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
1866 if (buf[0] == '\0') {
1867 pstrcpy(buf, sizeof(buf), "10.0.2.15");
1869 if (!inet_aton(buf, &guest_addr))
1872 guest_port = strtol(p, &r, 0);
1876 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
1877 fprintf(stderr, "qemu: could not set up redirection\n");
1882 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
1890 static void smb_exit(void)
1894 char filename[1024];
1896 /* erase all the files in the directory */
1897 d = opendir(smb_dir);
1902 if (strcmp(de->d_name, ".") != 0 &&
1903 strcmp(de->d_name, "..") != 0) {
1904 snprintf(filename, sizeof(filename), "%s/%s",
1905 smb_dir, de->d_name);
1913 /* automatic user mode samba server configuration */
1914 void net_slirp_smb(const char *exported_dir)
1916 char smb_conf[1024];
1917 char smb_cmdline[1024];
1920 if (!slirp_inited) {
1925 /* XXX: better tmp dir construction */
1926 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
1927 if (mkdir(smb_dir, 0700) < 0) {
1928 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
1931 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
1933 f = fopen(smb_conf, "w");
1935 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
1942 "socket address=127.0.0.1\n"
1943 "pid directory=%s\n"
1944 "lock directory=%s\n"
1945 "log file=%s/log.smbd\n"
1946 "smb passwd file=%s/smbpasswd\n"
1947 "security = share\n"
1962 snprintf(smb_cmdline, sizeof(smb_cmdline), "/usr/sbin/smbd -s %s",
1965 slirp_add_exec(0, smb_cmdline, 4, 139);
1968 #endif /* !defined(_WIN32) */
1970 #endif /* CONFIG_SLIRP */
1972 #if !defined(_WIN32)
1974 typedef struct TAPState {
1975 VLANClientState *vc;
1979 static void tap_receive(void *opaque, const uint8_t *buf, int size)
1981 TAPState *s = opaque;
1984 ret = write(s->fd, buf, size);
1985 if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
1992 static void tap_send(void *opaque)
1994 TAPState *s = opaque;
1998 size = read(s->fd, buf, sizeof(buf));
2000 qemu_send_packet(s->vc, buf, size);
2006 static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
2010 s = qemu_mallocz(sizeof(TAPState));
2014 s->vc = qemu_new_vlan_client(vlan, tap_receive, s);
2015 qemu_set_fd_handler(s->fd, tap_send, NULL, s);
2016 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
2021 static int tap_open(char *ifname, int ifname_size)
2027 fd = open("/dev/tap", O_RDWR);
2029 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
2034 dev = devname(s.st_rdev, S_IFCHR);
2035 pstrcpy(ifname, ifname_size, dev);
2037 fcntl(fd, F_SETFL, O_NONBLOCK);
2041 static int tap_open(char *ifname, int ifname_size)
2046 fd = open("/dev/net/tun", O_RDWR);
2048 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
2051 memset(&ifr, 0, sizeof(ifr));
2052 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
2053 if (ifname[0] != '\0')
2054 pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
2056 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
2057 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
2059 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
2063 pstrcpy(ifname, ifname_size, ifr.ifr_name);
2064 fcntl(fd, F_SETFL, O_NONBLOCK);
2069 static int net_tap_init(VLANState *vlan, const char *ifname1,
2070 const char *setup_script)
2073 int pid, status, fd;
2078 if (ifname1 != NULL)
2079 pstrcpy(ifname, sizeof(ifname), ifname1);
2082 fd = tap_open(ifname, sizeof(ifname));
2088 if (setup_script[0] != '\0') {
2089 /* try to launch network init script */
2094 *parg++ = (char *)setup_script;
2097 execv(setup_script, args);
2100 while (waitpid(pid, &status, 0) != pid);
2101 if (!WIFEXITED(status) ||
2102 WEXITSTATUS(status) != 0) {
2103 fprintf(stderr, "%s: could not launch network script\n",
2109 s = net_tap_fd_init(vlan, fd);
2112 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
2113 "tap: ifname=%s setup_script=%s", ifname, setup_script);
2117 /* network connection */
2118 typedef struct NetSocketState {
2119 VLANClientState *vc;
2121 int state; /* 0 = getting length, 1 = getting data */
2127 typedef struct NetSocketListenState {
2130 } NetSocketListenState;
2132 /* XXX: we consider we can send the whole packet without blocking */
2133 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
2135 NetSocketState *s = opaque;
2139 unix_write(s->fd, (const uint8_t *)&len, sizeof(len));
2140 unix_write(s->fd, buf, size);
2143 static void net_socket_send(void *opaque)
2145 NetSocketState *s = opaque;
2150 size = read(s->fd, buf1, sizeof(buf1));
2154 /* end of connection */
2155 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2160 /* reassemble a packet from the network */
2166 memcpy(s->buf + s->index, buf, l);
2170 if (s->index == 4) {
2172 s->packet_len = ntohl(*(uint32_t *)s->buf);
2178 l = s->packet_len - s->index;
2181 memcpy(s->buf + s->index, buf, l);
2185 if (s->index >= s->packet_len) {
2186 qemu_send_packet(s->vc, s->buf, s->packet_len);
2195 static void net_socket_connect(void *opaque)
2197 NetSocketState *s = opaque;
2198 qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
2201 static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
2205 s = qemu_mallocz(sizeof(NetSocketState));
2209 s->vc = qemu_new_vlan_client(vlan,
2210 net_socket_receive, s);
2211 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
2212 "socket: fd=%d", fd);
2214 net_socket_connect(s);
2216 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
2221 static void net_socket_accept(void *opaque)
2223 NetSocketListenState *s = opaque;
2225 struct sockaddr_in saddr;
2230 len = sizeof(saddr);
2231 fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
2232 if (fd < 0 && errno != EINTR) {
2234 } else if (fd >= 0) {
2238 s1 = net_socket_fd_init(s->vlan, fd, 1);
2242 snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
2243 "socket: connection from %s:%d",
2244 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
2248 static int net_socket_listen_init(VLANState *vlan, const char *host_str)
2250 NetSocketListenState *s;
2252 struct sockaddr_in saddr;
2254 if (parse_host_port(&saddr, host_str) < 0)
2257 s = qemu_mallocz(sizeof(NetSocketListenState));
2261 fd = socket(PF_INET, SOCK_STREAM, 0);
2266 fcntl(fd, F_SETFL, O_NONBLOCK);
2268 /* allow fast reuse */
2270 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val));
2272 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
2277 ret = listen(fd, 0);
2284 qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
2288 static int net_socket_connect_init(VLANState *vlan, const char *host_str)
2291 int fd, connected, ret;
2292 struct sockaddr_in saddr;
2294 if (parse_host_port(&saddr, host_str) < 0)
2297 fd = socket(PF_INET, SOCK_STREAM, 0);
2302 fcntl(fd, F_SETFL, O_NONBLOCK);
2306 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
2308 if (errno == EINTR || errno == EAGAIN) {
2309 } else if (errno == EINPROGRESS) {
2321 s = net_socket_fd_init(vlan, fd, connected);
2324 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
2325 "socket: connect to %s:%d",
2326 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
2330 #endif /* !_WIN32 */
2332 static int get_param_value(char *buf, int buf_size,
2333 const char *tag, const char *str)
2342 while (*p != '\0' && *p != '=') {
2343 if ((q - option) < sizeof(option) - 1)
2351 if (!strcmp(tag, option)) {
2353 while (*p != '\0' && *p != ',') {
2354 if ((q - buf) < buf_size - 1)
2361 while (*p != '\0' && *p != ',') {
2372 int net_client_init(const char *str)
2383 while (*p != '\0' && *p != ',') {
2384 if ((q - device) < sizeof(device) - 1)
2392 if (get_param_value(buf, sizeof(buf), "vlan", p)) {
2393 vlan_id = strtol(buf, NULL, 0);
2395 vlan = qemu_find_vlan(vlan_id);
2397 fprintf(stderr, "Could not create vlan %d\n", vlan_id);
2400 if (!strcmp(device, "nic")) {
2404 if (nb_nics >= MAX_NICS) {
2405 fprintf(stderr, "Too Many NICs\n");
2408 nd = &nd_table[nb_nics];
2409 macaddr = nd->macaddr;
2415 macaddr[5] = 0x56 + nb_nics;
2417 if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
2418 if (parse_macaddr(macaddr, buf) < 0) {
2419 fprintf(stderr, "invalid syntax for ethernet address\n");
2427 if (!strcmp(device, "none")) {
2428 /* does nothing. It is needed to signal that no network cards
2433 if (!strcmp(device, "user")) {
2434 ret = net_slirp_init(vlan);
2438 if (!strcmp(device, "tap")) {
2440 char setup_script[1024];
2442 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
2443 fd = strtol(buf, NULL, 0);
2445 if (net_tap_fd_init(vlan, fd))
2448 get_param_value(ifname, sizeof(ifname), "ifname", p);
2449 if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
2450 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
2452 ret = net_tap_init(vlan, ifname, setup_script);
2455 if (!strcmp(device, "socket")) {
2456 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
2458 fd = strtol(buf, NULL, 0);
2460 if (net_socket_fd_init(vlan, fd, 1))
2462 } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
2463 ret = net_socket_listen_init(vlan, buf);
2464 } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
2465 ret = net_socket_connect_init(vlan, buf);
2467 fprintf(stderr, "Unknown socket options: %s\n", p);
2473 fprintf(stderr, "Unknown network device: %s\n", device);
2477 fprintf(stderr, "Could not initialize device '%s'\n", device);
2483 void do_info_network(void)
2486 VLANClientState *vc;
2488 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
2489 term_printf("VLAN %d devices:\n", vlan->id);
2490 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
2491 term_printf(" %s\n", vc->info_str);
2495 /***********************************************************/
2498 static int usb_device_add(const char *devname)
2506 for(i = 0;i < MAX_VM_USB_PORTS; i++) {
2507 if (!vm_usb_ports[i]->dev)
2510 if (i == MAX_VM_USB_PORTS)
2513 if (strstart(devname, "host:", &p)) {
2514 dev = usb_host_device_open(p);
2517 } else if (!strcmp(devname, "mouse")) {
2518 dev = usb_mouse_init();
2524 usb_attach(vm_usb_ports[i], dev);
2528 static int usb_device_del(const char *devname)
2531 int bus_num, addr, i;
2537 p = strchr(devname, '.');
2540 bus_num = strtoul(devname, NULL, 0);
2541 addr = strtoul(p + 1, NULL, 0);
2544 for(i = 0;i < MAX_VM_USB_PORTS; i++) {
2545 dev = vm_usb_ports[i]->dev;
2546 if (dev && dev->addr == addr)
2549 if (i == MAX_VM_USB_PORTS)
2551 usb_attach(vm_usb_ports[i], NULL);
2555 void do_usb_add(const char *devname)
2558 ret = usb_device_add(devname);
2560 term_printf("Could not add USB device '%s'\n", devname);
2563 void do_usb_del(const char *devname)
2566 ret = usb_device_del(devname);
2568 term_printf("Could not remove USB device '%s'\n", devname);
2575 const char *speed_str;
2578 term_printf("USB support not enabled\n");
2582 for(i = 0; i < MAX_VM_USB_PORTS; i++) {
2583 dev = vm_usb_ports[i]->dev;
2585 term_printf("Hub port %d:\n", i);
2586 switch(dev->speed) {
2590 case USB_SPEED_FULL:
2593 case USB_SPEED_HIGH:
2600 term_printf(" Device %d.%d, speed %s Mb/s\n",
2601 0, dev->addr, speed_str);
2606 /***********************************************************/
2609 static char *pid_filename;
2611 /* Remove PID file. Called on normal exit */
2613 static void remove_pidfile(void)
2615 unlink (pid_filename);
2618 static void create_pidfile(const char *filename)
2620 struct stat pidstat;
2623 /* Try to write our PID to the named file */
2624 if (stat(filename, &pidstat) < 0) {
2625 if (errno == ENOENT) {
2626 if ((f = fopen (filename, "w")) == NULL) {
2627 perror("Opening pidfile");
2630 fprintf(f, "%d\n", getpid());
2632 pid_filename = qemu_strdup(filename);
2633 if (!pid_filename) {
2634 fprintf(stderr, "Could not save PID filename");
2637 atexit(remove_pidfile);
2640 fprintf(stderr, "%s already exists. Remove it and try again.\n",
2646 /***********************************************************/
2649 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
2653 static void dumb_resize(DisplayState *ds, int w, int h)
2657 static void dumb_refresh(DisplayState *ds)
2659 vga_update_display();
2662 void dumb_display_init(DisplayState *ds)
2667 ds->dpy_update = dumb_update;
2668 ds->dpy_resize = dumb_resize;
2669 ds->dpy_refresh = dumb_refresh;
2672 #if !defined(CONFIG_SOFTMMU)
2673 /***********************************************************/
2674 /* cpu signal handler */
2675 static void host_segv_handler(int host_signum, siginfo_t *info,
2678 if (cpu_signal_handler(host_signum, info, puc))
2680 if (stdio_nb_clients > 0)
2686 /***********************************************************/
2689 #define MAX_IO_HANDLERS 64
2691 typedef struct IOHandlerRecord {
2693 IOCanRWHandler *fd_read_poll;
2695 IOHandler *fd_write;
2697 /* temporary data */
2699 struct IOHandlerRecord *next;
2702 static IOHandlerRecord *first_io_handler;
2704 /* XXX: fd_read_poll should be suppressed, but an API change is
2705 necessary in the character devices to suppress fd_can_read(). */
2706 int qemu_set_fd_handler2(int fd,
2707 IOCanRWHandler *fd_read_poll,
2709 IOHandler *fd_write,
2712 IOHandlerRecord **pioh, *ioh;
2714 if (!fd_read && !fd_write) {
2715 pioh = &first_io_handler;
2720 if (ioh->fd == fd) {
2727 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2731 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
2734 ioh->next = first_io_handler;
2735 first_io_handler = ioh;
2738 ioh->fd_read_poll = fd_read_poll;
2739 ioh->fd_read = fd_read;
2740 ioh->fd_write = fd_write;
2741 ioh->opaque = opaque;
2746 int qemu_set_fd_handler(int fd,
2748 IOHandler *fd_write,
2751 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
2754 /***********************************************************/
2755 /* savevm/loadvm support */
2757 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
2759 fwrite(buf, 1, size, f);
2762 void qemu_put_byte(QEMUFile *f, int v)
2767 void qemu_put_be16(QEMUFile *f, unsigned int v)
2769 qemu_put_byte(f, v >> 8);
2770 qemu_put_byte(f, v);
2773 void qemu_put_be32(QEMUFile *f, unsigned int v)
2775 qemu_put_byte(f, v >> 24);
2776 qemu_put_byte(f, v >> 16);
2777 qemu_put_byte(f, v >> 8);
2778 qemu_put_byte(f, v);
2781 void qemu_put_be64(QEMUFile *f, uint64_t v)
2783 qemu_put_be32(f, v >> 32);
2784 qemu_put_be32(f, v);
2787 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size)
2789 return fread(buf, 1, size, f);
2792 int qemu_get_byte(QEMUFile *f)
2802 unsigned int qemu_get_be16(QEMUFile *f)
2805 v = qemu_get_byte(f) << 8;
2806 v |= qemu_get_byte(f);
2810 unsigned int qemu_get_be32(QEMUFile *f)
2813 v = qemu_get_byte(f) << 24;
2814 v |= qemu_get_byte(f) << 16;
2815 v |= qemu_get_byte(f) << 8;
2816 v |= qemu_get_byte(f);
2820 uint64_t qemu_get_be64(QEMUFile *f)
2823 v = (uint64_t)qemu_get_be32(f) << 32;
2824 v |= qemu_get_be32(f);
2828 int64_t qemu_ftell(QEMUFile *f)
2833 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
2835 if (fseek(f, pos, whence) < 0)
2840 typedef struct SaveStateEntry {
2844 SaveStateHandler *save_state;
2845 LoadStateHandler *load_state;
2847 struct SaveStateEntry *next;
2850 static SaveStateEntry *first_se;
2852 int register_savevm(const char *idstr,
2855 SaveStateHandler *save_state,
2856 LoadStateHandler *load_state,
2859 SaveStateEntry *se, **pse;
2861 se = qemu_malloc(sizeof(SaveStateEntry));
2864 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
2865 se->instance_id = instance_id;
2866 se->version_id = version_id;
2867 se->save_state = save_state;
2868 se->load_state = load_state;
2869 se->opaque = opaque;
2872 /* add at the end of list */
2874 while (*pse != NULL)
2875 pse = &(*pse)->next;
2880 #define QEMU_VM_FILE_MAGIC 0x5145564d
2881 #define QEMU_VM_FILE_VERSION 0x00000001
2883 int qemu_savevm(const char *filename)
2887 int len, len_pos, cur_pos, saved_vm_running, ret;
2889 saved_vm_running = vm_running;
2892 f = fopen(filename, "wb");
2898 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
2899 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
2901 for(se = first_se; se != NULL; se = se->next) {
2903 len = strlen(se->idstr);
2904 qemu_put_byte(f, len);
2905 qemu_put_buffer(f, se->idstr, len);
2907 qemu_put_be32(f, se->instance_id);
2908 qemu_put_be32(f, se->version_id);
2910 /* record size: filled later */
2912 qemu_put_be32(f, 0);
2914 se->save_state(f, se->opaque);
2916 /* fill record size */
2918 len = ftell(f) - len_pos - 4;
2919 fseek(f, len_pos, SEEK_SET);
2920 qemu_put_be32(f, len);
2921 fseek(f, cur_pos, SEEK_SET);
2927 if (saved_vm_running)
2932 static SaveStateEntry *find_se(const char *idstr, int instance_id)
2936 for(se = first_se; se != NULL; se = se->next) {
2937 if (!strcmp(se->idstr, idstr) &&
2938 instance_id == se->instance_id)
2944 int qemu_loadvm(const char *filename)
2948 int len, cur_pos, ret, instance_id, record_len, version_id;
2949 int saved_vm_running;
2953 saved_vm_running = vm_running;
2956 f = fopen(filename, "rb");
2962 v = qemu_get_be32(f);
2963 if (v != QEMU_VM_FILE_MAGIC)
2965 v = qemu_get_be32(f);
2966 if (v != QEMU_VM_FILE_VERSION) {
2973 #if defined (DO_TB_FLUSH)
2974 tb_flush(global_env);
2976 len = qemu_get_byte(f);
2979 qemu_get_buffer(f, idstr, len);
2981 instance_id = qemu_get_be32(f);
2982 version_id = qemu_get_be32(f);
2983 record_len = qemu_get_be32(f);
2985 printf("idstr=%s instance=0x%x version=%d len=%d\n",
2986 idstr, instance_id, version_id, record_len);
2989 se = find_se(idstr, instance_id);
2991 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
2992 instance_id, idstr);
2994 ret = se->load_state(f, se->opaque, version_id);
2996 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
2997 instance_id, idstr);
3000 /* always seek to exact end of record */
3001 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
3006 if (saved_vm_running)
3011 /***********************************************************/
3012 /* cpu save/restore */
3014 #if defined(TARGET_I386)
3016 static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
3018 qemu_put_be32(f, dt->selector);
3019 qemu_put_betl(f, dt->base);
3020 qemu_put_be32(f, dt->limit);
3021 qemu_put_be32(f, dt->flags);
3024 static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
3026 dt->selector = qemu_get_be32(f);
3027 dt->base = qemu_get_betl(f);
3028 dt->limit = qemu_get_be32(f);
3029 dt->flags = qemu_get_be32(f);
3032 void cpu_save(QEMUFile *f, void *opaque)
3034 CPUState *env = opaque;
3035 uint16_t fptag, fpus, fpuc, fpregs_format;
3039 for(i = 0; i < CPU_NB_REGS; i++)
3040 qemu_put_betls(f, &env->regs[i]);
3041 qemu_put_betls(f, &env->eip);
3042 qemu_put_betls(f, &env->eflags);
3043 hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
3044 qemu_put_be32s(f, &hflags);
3048 fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
3050 for(i = 0; i < 8; i++) {
3051 fptag |= ((!env->fptags[i]) << i);
3054 qemu_put_be16s(f, &fpuc);
3055 qemu_put_be16s(f, &fpus);
3056 qemu_put_be16s(f, &fptag);
3058 #ifdef USE_X86LDOUBLE
3063 qemu_put_be16s(f, &fpregs_format);
3065 for(i = 0; i < 8; i++) {
3066 #ifdef USE_X86LDOUBLE
3070 /* we save the real CPU data (in case of MMX usage only 'mant'
3071 contains the MMX register */
3072 cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
3073 qemu_put_be64(f, mant);
3074 qemu_put_be16(f, exp);
3077 /* if we use doubles for float emulation, we save the doubles to
3078 avoid losing information in case of MMX usage. It can give
3079 problems if the image is restored on a CPU where long
3080 doubles are used instead. */
3081 qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
3085 for(i = 0; i < 6; i++)
3086 cpu_put_seg(f, &env->segs[i]);
3087 cpu_put_seg(f, &env->ldt);
3088 cpu_put_seg(f, &env->tr);
3089 cpu_put_seg(f, &env->gdt);
3090 cpu_put_seg(f, &env->idt);
3092 qemu_put_be32s(f, &env->sysenter_cs);
3093 qemu_put_be32s(f, &env->sysenter_esp);
3094 qemu_put_be32s(f, &env->sysenter_eip);
3096 qemu_put_betls(f, &env->cr[0]);
3097 qemu_put_betls(f, &env->cr[2]);
3098 qemu_put_betls(f, &env->cr[3]);
3099 qemu_put_betls(f, &env->cr[4]);
3101 for(i = 0; i < 8; i++)
3102 qemu_put_betls(f, &env->dr[i]);
3105 qemu_put_be32s(f, &env->a20_mask);
3108 qemu_put_be32s(f, &env->mxcsr);
3109 for(i = 0; i < CPU_NB_REGS; i++) {
3110 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
3111 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
3114 #ifdef TARGET_X86_64
3115 qemu_put_be64s(f, &env->efer);
3116 qemu_put_be64s(f, &env->star);
3117 qemu_put_be64s(f, &env->lstar);
3118 qemu_put_be64s(f, &env->cstar);
3119 qemu_put_be64s(f, &env->fmask);
3120 qemu_put_be64s(f, &env->kernelgsbase);
3124 #ifdef USE_X86LDOUBLE
3125 /* XXX: add that in a FPU generic layer */
3126 union x86_longdouble {
3131 #define MANTD1(fp) (fp & ((1LL << 52) - 1))
3132 #define EXPBIAS1 1023
3133 #define EXPD1(fp) ((fp >> 52) & 0x7FF)
3134 #define SIGND1(fp) ((fp >> 32) & 0x80000000)
3136 static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
3140 p->mant = (MANTD1(temp) << 11) | (1LL << 63);
3141 /* exponent + sign */
3142 e = EXPD1(temp) - EXPBIAS1 + 16383;
3143 e |= SIGND1(temp) >> 16;
3148 int cpu_load(QEMUFile *f, void *opaque, int version_id)
3150 CPUState *env = opaque;
3153 uint16_t fpus, fpuc, fptag, fpregs_format;
3155 if (version_id != 3)
3157 for(i = 0; i < CPU_NB_REGS; i++)
3158 qemu_get_betls(f, &env->regs[i]);
3159 qemu_get_betls(f, &env->eip);
3160 qemu_get_betls(f, &env->eflags);
3161 qemu_get_be32s(f, &hflags);
3163 qemu_get_be16s(f, &fpuc);
3164 qemu_get_be16s(f, &fpus);
3165 qemu_get_be16s(f, &fptag);
3166 qemu_get_be16s(f, &fpregs_format);
3168 /* NOTE: we cannot always restore the FPU state if the image come
3169 from a host with a different 'USE_X86LDOUBLE' define. We guess
3170 if we are in an MMX state to restore correctly in that case. */
3171 guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
3172 for(i = 0; i < 8; i++) {
3176 switch(fpregs_format) {
3178 mant = qemu_get_be64(f);
3179 exp = qemu_get_be16(f);
3180 #ifdef USE_X86LDOUBLE
3181 env->fpregs[i].d = cpu_set_fp80(mant, exp);
3183 /* difficult case */
3185 env->fpregs[i].mmx.MMX_Q(0) = mant;
3187 env->fpregs[i].d = cpu_set_fp80(mant, exp);
3191 mant = qemu_get_be64(f);
3192 #ifdef USE_X86LDOUBLE
3194 union x86_longdouble *p;
3195 /* difficult case */
3196 p = (void *)&env->fpregs[i];
3201 fp64_to_fp80(p, mant);
3205 env->fpregs[i].mmx.MMX_Q(0) = mant;
3214 /* XXX: restore FPU round state */
3215 env->fpstt = (fpus >> 11) & 7;
3216 env->fpus = fpus & ~0x3800;
3218 for(i = 0; i < 8; i++) {
3219 env->fptags[i] = (fptag >> i) & 1;
3222 for(i = 0; i < 6; i++)
3223 cpu_get_seg(f, &env->segs[i]);
3224 cpu_get_seg(f, &env->ldt);
3225 cpu_get_seg(f, &env->tr);
3226 cpu_get_seg(f, &env->gdt);
3227 cpu_get_seg(f, &env->idt);
3229 qemu_get_be32s(f, &env->sysenter_cs);
3230 qemu_get_be32s(f, &env->sysenter_esp);
3231 qemu_get_be32s(f, &env->sysenter_eip);
3233 qemu_get_betls(f, &env->cr[0]);
3234 qemu_get_betls(f, &env->cr[2]);
3235 qemu_get_betls(f, &env->cr[3]);
3236 qemu_get_betls(f, &env->cr[4]);
3238 for(i = 0; i < 8; i++)
3239 qemu_get_betls(f, &env->dr[i]);
3242 qemu_get_be32s(f, &env->a20_mask);
3244 qemu_get_be32s(f, &env->mxcsr);
3245 for(i = 0; i < CPU_NB_REGS; i++) {
3246 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
3247 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
3250 #ifdef TARGET_X86_64
3251 qemu_get_be64s(f, &env->efer);
3252 qemu_get_be64s(f, &env->star);
3253 qemu_get_be64s(f, &env->lstar);
3254 qemu_get_be64s(f, &env->cstar);
3255 qemu_get_be64s(f, &env->fmask);
3256 qemu_get_be64s(f, &env->kernelgsbase);
3259 /* XXX: compute hflags from scratch, except for CPL and IIF */
3260 env->hflags = hflags;
3265 #elif defined(TARGET_PPC)
3266 void cpu_save(QEMUFile *f, void *opaque)
3270 int cpu_load(QEMUFile *f, void *opaque, int version_id)
3275 #elif defined(TARGET_MIPS)
3276 void cpu_save(QEMUFile *f, void *opaque)
3280 int cpu_load(QEMUFile *f, void *opaque, int version_id)
3285 #elif defined(TARGET_SPARC)
3286 void cpu_save(QEMUFile *f, void *opaque)
3288 CPUState *env = opaque;
3292 for(i = 0; i < 8; i++)
3293 qemu_put_betls(f, &env->gregs[i]);
3294 for(i = 0; i < NWINDOWS * 16; i++)
3295 qemu_put_betls(f, &env->regbase[i]);
3298 for(i = 0; i < TARGET_FPREGS; i++) {
3304 qemu_put_betl(f, u.i);
3307 qemu_put_betls(f, &env->pc);
3308 qemu_put_betls(f, &env->npc);
3309 qemu_put_betls(f, &env->y);
3311 qemu_put_be32(f, tmp);
3312 qemu_put_betls(f, &env->fsr);
3313 qemu_put_betls(f, &env->tbr);
3314 #ifndef TARGET_SPARC64
3315 qemu_put_be32s(f, &env->wim);
3317 for(i = 0; i < 16; i++)
3318 qemu_put_be32s(f, &env->mmuregs[i]);
3322 int cpu_load(QEMUFile *f, void *opaque, int version_id)
3324 CPUState *env = opaque;
3328 for(i = 0; i < 8; i++)
3329 qemu_get_betls(f, &env->gregs[i]);
3330 for(i = 0; i < NWINDOWS * 16; i++)
3331 qemu_get_betls(f, &env->regbase[i]);
3334 for(i = 0; i < TARGET_FPREGS; i++) {
3339 u.i = qemu_get_betl(f);
3343 qemu_get_betls(f, &env->pc);
3344 qemu_get_betls(f, &env->npc);
3345 qemu_get_betls(f, &env->y);
3346 tmp = qemu_get_be32(f);
3347 env->cwp = 0; /* needed to ensure that the wrapping registers are
3348 correctly updated */
3350 qemu_get_betls(f, &env->fsr);
3351 qemu_get_betls(f, &env->tbr);
3352 #ifndef TARGET_SPARC64
3353 qemu_get_be32s(f, &env->wim);
3355 for(i = 0; i < 16; i++)
3356 qemu_get_be32s(f, &env->mmuregs[i]);
3363 #warning No CPU save/restore functions
3367 /***********************************************************/
3368 /* ram save/restore */
3370 /* we just avoid storing empty pages */
3371 static void ram_put_page(QEMUFile *f, const uint8_t *buf, int len)
3376 for(i = 1; i < len; i++) {
3380 qemu_put_byte(f, 1);
3381 qemu_put_byte(f, v);
3384 qemu_put_byte(f, 0);
3385 qemu_put_buffer(f, buf, len);
3388 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
3392 v = qemu_get_byte(f);
3395 if (qemu_get_buffer(f, buf, len) != len)
3399 v = qemu_get_byte(f);
3400 memset(buf, v, len);
3408 static void ram_save(QEMUFile *f, void *opaque)
3411 qemu_put_be32(f, phys_ram_size);
3412 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
3413 ram_put_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
3417 static int ram_load(QEMUFile *f, void *opaque, int version_id)
3421 if (version_id != 1)
3423 if (qemu_get_be32(f) != phys_ram_size)
3425 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
3426 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
3433 /***********************************************************/
3434 /* machine registration */
3436 QEMUMachine *first_machine = NULL;
3438 int qemu_register_machine(QEMUMachine *m)
3441 pm = &first_machine;
3449 QEMUMachine *find_machine(const char *name)
3453 for(m = first_machine; m != NULL; m = m->next) {
3454 if (!strcmp(m->name, name))
3460 /***********************************************************/
3461 /* main execution loop */
3463 void gui_update(void *opaque)
3465 display_state.dpy_refresh(&display_state);
3466 qemu_mod_timer(gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
3469 struct vm_change_state_entry {
3470 VMChangeStateHandler *cb;
3472 LIST_ENTRY (vm_change_state_entry) entries;
3475 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3477 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3480 VMChangeStateEntry *e;
3482 e = qemu_mallocz(sizeof (*e));
3488 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3492 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3494 LIST_REMOVE (e, entries);
3498 static void vm_state_notify(int running)
3500 VMChangeStateEntry *e;
3502 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3503 e->cb(e->opaque, running);
3507 /* XXX: support several handlers */
3508 static VMStopHandler *vm_stop_cb;
3509 static void *vm_stop_opaque;
3511 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
3514 vm_stop_opaque = opaque;
3518 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
3532 void vm_stop(int reason)
3535 cpu_disable_ticks();
3539 vm_stop_cb(vm_stop_opaque, reason);
3546 /* reset/shutdown handler */
3548 typedef struct QEMUResetEntry {
3549 QEMUResetHandler *func;
3551 struct QEMUResetEntry *next;
3554 static QEMUResetEntry *first_reset_entry;
3555 static int reset_requested;
3556 static int shutdown_requested;
3557 static int powerdown_requested;
3559 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
3561 QEMUResetEntry **pre, *re;
3563 pre = &first_reset_entry;
3564 while (*pre != NULL)
3565 pre = &(*pre)->next;
3566 re = qemu_mallocz(sizeof(QEMUResetEntry));
3568 re->opaque = opaque;
3573 void qemu_system_reset(void)
3577 /* reset all devices */
3578 for(re = first_reset_entry; re != NULL; re = re->next) {
3579 re->func(re->opaque);
3583 void qemu_system_reset_request(void)
3585 reset_requested = 1;
3586 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
3589 void qemu_system_shutdown_request(void)
3591 shutdown_requested = 1;
3592 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
3595 void qemu_system_powerdown_request(void)
3597 powerdown_requested = 1;
3598 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
3601 static void main_cpu_reset(void *opaque)
3603 #if defined(TARGET_I386) || defined(TARGET_SPARC)
3604 CPUState *env = opaque;
3609 void main_loop_wait(int timeout)
3612 struct pollfd ufds[MAX_IO_HANDLERS + 1], *pf;
3613 IOHandlerRecord *ioh, *ioh_next;
3621 /* poll any events */
3622 /* XXX: separate device handlers from system ones */
3624 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3628 (!ioh->fd_read_poll ||
3629 ioh->fd_read_poll(ioh->opaque) != 0)) {
3630 pf->events |= POLLIN;
3632 if (ioh->fd_write) {
3633 pf->events |= POLLOUT;
3639 ret = poll(ufds, pf - ufds, timeout);
3641 /* XXX: better handling of removal */
3642 for(ioh = first_io_handler; ioh != NULL; ioh = ioh_next) {
3643 ioh_next = ioh->next;
3645 if (pf->revents & POLLIN) {
3646 ioh->fd_read(ioh->opaque);
3648 if (pf->revents & POLLOUT) {
3649 ioh->fd_write(ioh->opaque);
3653 #endif /* !defined(_WIN32) */
3654 #if defined(CONFIG_SLIRP)
3655 /* XXX: merge with poll() */
3657 fd_set rfds, wfds, xfds;
3665 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
3668 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
3670 slirp_select_poll(&rfds, &wfds, &xfds);
3676 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
3677 qemu_get_clock(vm_clock));
3678 /* run dma transfers, if any */
3682 /* real time timers */
3683 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
3684 qemu_get_clock(rt_clock));
3690 CPUState *env = global_env;
3694 ret = cpu_exec(env);
3695 if (shutdown_requested) {
3696 ret = EXCP_INTERRUPT;
3699 if (reset_requested) {
3700 reset_requested = 0;
3701 qemu_system_reset();
3702 ret = EXCP_INTERRUPT;
3704 if (powerdown_requested) {
3705 powerdown_requested = 0;
3706 qemu_system_powerdown();
3707 ret = EXCP_INTERRUPT;
3709 if (ret == EXCP_DEBUG) {
3710 vm_stop(EXCP_DEBUG);
3712 /* if hlt instruction, we wait until the next IRQ */
3713 /* XXX: use timeout computed from timers */
3714 if (ret == EXCP_HLT)
3721 main_loop_wait(timeout);
3723 cpu_disable_ticks();
3729 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2005 Fabrice Bellard\n"
3730 "usage: %s [options] [disk_image]\n"
3732 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
3734 "Standard options:\n"
3735 "-M machine select emulated machine (-M ? for list)\n"
3736 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
3737 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
3738 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
3739 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
3740 "-boot [a|c|d] boot on floppy (a), hard disk (c) or CD-ROM (d)\n"
3741 "-snapshot write to temporary files instead of disk image files\n"
3742 "-m megs set virtual RAM size to megs MB [default=%d]\n"
3743 "-nographic disable graphical output and redirect serial I/Os to console\n"
3745 "-k language use keyboard layout (for example \"fr\" for French)\n"
3748 "-enable-audio enable audio support, and all the sound cars\n"
3749 "-audio-help print list of audio drivers and their options\n"
3750 "-soundhw c1,... enable audio support\n"
3751 " and only specified sound cards (comma separated list)\n"
3752 " use -soundhw ? to get the list of supported cards\n"
3754 "-localtime set the real time clock to local time [default=utc]\n"
3755 "-full-screen start in full screen\n"
3757 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
3759 "-usb enable the USB driver (will be the default soon)\n"
3760 "-usbdevice name add the host or guest USB device 'name'\n"
3761 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
3762 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
3765 "Network options:\n"
3766 "-net nic[,vlan=n][,macaddr=addr]\n"
3767 " create a new Network Interface Card and connect it to VLAN 'n'\n"
3769 "-net user[,vlan=n]\n"
3770 " connect the user mode network stack to VLAN 'n'\n"
3773 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file]\n"
3774 " connect the host TAP network interface to VLAN 'n' and use\n"
3775 " the network script 'file' (default=%s);\n"
3776 " use 'fd=h' to connect to an already opened TAP interface\n"
3777 "-net socket[,vlan=n][,fd=x][,listen=[host]:port][,connect=host:port]\n"
3778 " connect the vlan 'n' to another VLAN using a socket connection\n"
3780 "-net none use it alone to have zero network devices; if no -net option\n"
3781 " is provided, the default is '-net nic -net user'\n"
3784 "-tftp prefix allow tftp access to files starting with prefix [-net user]\n"
3786 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
3788 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
3789 " redirect TCP or UDP connections from host to guest [-net user]\n"
3792 "Linux boot specific:\n"
3793 "-kernel bzImage use 'bzImage' as kernel image\n"
3794 "-append cmdline use 'cmdline' as kernel command line\n"
3795 "-initrd file use 'file' as initial ram disk\n"
3797 "Debug/Expert options:\n"
3798 "-monitor dev redirect the monitor to char device 'dev'\n"
3799 "-serial dev redirect the serial port to char device 'dev'\n"
3800 "-parallel dev redirect the parallel port to char device 'dev'\n"
3801 "-pidfile file Write PID to 'file'\n"
3802 "-S freeze CPU at startup (use 'c' to start execution)\n"
3803 "-s wait gdb connection to port %d\n"
3804 "-p port change gdb connection port\n"
3805 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
3806 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
3807 " translation (t=none or lba) (usually qemu can guess them)\n"
3808 "-L path set the directory for the BIOS and VGA BIOS\n"
3810 "-no-kqemu disable KQEMU kernel module usage\n"
3812 #ifdef USE_CODE_COPY
3813 "-no-code-copy disable code copy acceleration\n"
3816 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
3817 " (default is CL-GD5446 PCI VGA)\n"
3819 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
3821 "During emulation, the following keys are useful:\n"
3822 "ctrl-alt-f toggle full screen\n"
3823 "ctrl-alt-n switch to virtual console 'n'\n"
3824 "ctrl-alt toggle mouse and keyboard grab\n"
3826 "When using -nographic, press 'ctrl-a h' to get some help.\n"
3828 #ifdef CONFIG_SOFTMMU
3835 DEFAULT_NETWORK_SCRIPT,
3837 DEFAULT_GDBSTUB_PORT,
3839 #ifndef CONFIG_SOFTMMU
3841 "NOTE: this version of QEMU is faster but it needs slightly patched OSes to\n"
3842 "work. Please use the 'qemu' executable to have a more accurate (but slower)\n"
3848 #define HAS_ARG 0x0001
3862 QEMU_OPTION_snapshot,
3864 QEMU_OPTION_nographic,
3866 QEMU_OPTION_enable_audio,
3867 QEMU_OPTION_audio_help,
3868 QEMU_OPTION_soundhw,
3886 QEMU_OPTION_no_code_copy,
3888 QEMU_OPTION_localtime,
3889 QEMU_OPTION_cirrusvga,
3891 QEMU_OPTION_std_vga,
3892 QEMU_OPTION_monitor,
3894 QEMU_OPTION_parallel,
3896 QEMU_OPTION_full_screen,
3897 QEMU_OPTION_pidfile,
3898 QEMU_OPTION_no_kqemu,
3899 QEMU_OPTION_win2k_hack,
3901 QEMU_OPTION_usbdevice,
3904 typedef struct QEMUOption {
3910 const QEMUOption qemu_options[] = {
3911 { "h", 0, QEMU_OPTION_h },
3913 { "M", HAS_ARG, QEMU_OPTION_M },
3914 { "fda", HAS_ARG, QEMU_OPTION_fda },
3915 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
3916 { "hda", HAS_ARG, QEMU_OPTION_hda },
3917 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
3918 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
3919 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
3920 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
3921 { "boot", HAS_ARG, QEMU_OPTION_boot },
3922 { "snapshot", 0, QEMU_OPTION_snapshot },
3923 { "m", HAS_ARG, QEMU_OPTION_m },
3924 { "nographic", 0, QEMU_OPTION_nographic },
3925 { "k", HAS_ARG, QEMU_OPTION_k },
3927 { "enable-audio", 0, QEMU_OPTION_enable_audio },
3928 { "audio-help", 0, QEMU_OPTION_audio_help },
3929 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
3932 { "net", HAS_ARG, QEMU_OPTION_net},
3934 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
3936 { "smb", HAS_ARG, QEMU_OPTION_smb },
3938 { "redir", HAS_ARG, QEMU_OPTION_redir },
3941 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
3942 { "append", HAS_ARG, QEMU_OPTION_append },
3943 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
3945 { "S", 0, QEMU_OPTION_S },
3946 { "s", 0, QEMU_OPTION_s },
3947 { "p", HAS_ARG, QEMU_OPTION_p },
3948 { "d", HAS_ARG, QEMU_OPTION_d },
3949 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
3950 { "L", HAS_ARG, QEMU_OPTION_L },
3951 { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
3953 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
3955 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
3956 { "g", 1, QEMU_OPTION_g },
3958 { "localtime", 0, QEMU_OPTION_localtime },
3959 { "std-vga", 0, QEMU_OPTION_std_vga },
3960 { "monitor", 1, QEMU_OPTION_monitor },
3961 { "serial", 1, QEMU_OPTION_serial },
3962 { "parallel", 1, QEMU_OPTION_parallel },
3963 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
3964 { "full-screen", 0, QEMU_OPTION_full_screen },
3965 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
3966 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
3967 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
3969 /* temporary options */
3970 { "usb", 0, QEMU_OPTION_usb },
3971 { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
3975 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
3977 /* this stack is only used during signal handling */
3978 #define SIGNAL_STACK_SIZE 32768
3980 static uint8_t *signal_stack;
3984 /* password input */
3986 static BlockDriverState *get_bdrv(int index)
3988 BlockDriverState *bs;
3991 bs = bs_table[index];
3992 } else if (index < 6) {
3993 bs = fd_table[index - 4];
4000 static void read_passwords(void)
4002 BlockDriverState *bs;
4006 for(i = 0; i < 6; i++) {
4008 if (bs && bdrv_is_encrypted(bs)) {
4009 term_printf("%s is encrypted.\n", bdrv_get_device_name(bs));
4010 for(j = 0; j < 3; j++) {
4011 monitor_readline("Password: ",
4012 1, password, sizeof(password));
4013 if (bdrv_set_key(bs, password) == 0)
4015 term_printf("invalid password\n");
4021 /* XXX: currently we cannot use simultaneously different CPUs */
4022 void register_machines(void)
4024 #if defined(TARGET_I386)
4025 qemu_register_machine(&pc_machine);
4026 qemu_register_machine(&isapc_machine);
4027 #elif defined(TARGET_PPC)
4028 qemu_register_machine(&heathrow_machine);
4029 qemu_register_machine(&core99_machine);
4030 qemu_register_machine(&prep_machine);
4031 #elif defined(TARGET_MIPS)
4032 qemu_register_machine(&mips_machine);
4033 #elif defined(TARGET_SPARC)
4034 #ifdef TARGET_SPARC64
4035 qemu_register_machine(&sun4u_machine);
4037 qemu_register_machine(&sun4m_machine);
4043 static void select_soundhw (const char *optarg)
4045 if (*optarg == '?') {
4047 printf ("Valid sound card names (comma separated):\n");
4048 printf ("sb16 Creative Sound Blaster 16\n");
4051 printf ("adlib Yamaha YMF262 (OPL3)\n");
4053 printf ("adlib Yamaha YM3812 (OPL2)\n");
4057 printf ("gus Gravis Ultrasound GF1\n");
4059 printf ("es1370 ENSONIQ AudioPCI ES1370\n");
4060 exit (*optarg != '?');
4067 { "sb16", &sb16_enabled },
4069 { "adlib", &adlib_enabled },
4072 { "gus", &gus_enabled },
4074 { "es1370", &es1370_enabled },
4076 size_t tablen, l, i;
4082 tablen = sizeof (soundhw_tab) / sizeof (soundhw_tab[0]);
4085 e = strchr (p, ',');
4086 l = !e ? strlen (p) : (size_t) (e - p);
4087 for (i = 0; i < tablen; ++i) {
4088 if (!strncmp (soundhw_tab[i].name, p, l)) {
4090 *soundhw_tab[i].enabledp = 1;
4097 "Unknown sound card name (too big to show)\n");
4100 fprintf (stderr, "Unknown sound card name `%.*s'\n",
4105 p += l + (e != NULL);
4109 goto show_valid_cards;
4114 #define MAX_NET_CLIENTS 32
4116 int main(int argc, char **argv)
4118 #ifdef CONFIG_GDBSTUB
4119 int use_gdbstub, gdbstub_port;
4122 int snapshot, linux_boot;
4124 const char *initrd_filename;
4125 const char *hd_filename[MAX_DISKS], *fd_filename[MAX_FD];
4126 const char *kernel_filename, *kernel_cmdline;
4127 DisplayState *ds = &display_state;
4128 int cyls, heads, secs, translation;
4129 int start_emulation = 1;
4130 char net_clients[MAX_NET_CLIENTS][256];
4133 const char *r, *optarg;
4134 CharDriverState *monitor_hd;
4135 char monitor_device[128];
4136 char serial_devices[MAX_SERIAL_PORTS][128];
4137 int serial_device_index;
4138 char parallel_devices[MAX_PARALLEL_PORTS][128];
4139 int parallel_device_index;
4140 const char *loadvm = NULL;
4141 QEMUMachine *machine;
4142 char usb_devices[MAX_VM_USB_PORTS][128];
4143 int usb_devices_index;
4145 LIST_INIT (&vm_change_state_head);
4146 #if !defined(CONFIG_SOFTMMU)
4147 /* we never want that malloc() uses mmap() */
4148 mallopt(M_MMAP_THRESHOLD, 4096 * 1024);
4150 register_machines();
4151 machine = first_machine;
4152 initrd_filename = NULL;
4153 for(i = 0; i < MAX_FD; i++)
4154 fd_filename[i] = NULL;
4155 for(i = 0; i < MAX_DISKS; i++)
4156 hd_filename[i] = NULL;
4157 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
4158 vga_ram_size = VGA_RAM_SIZE;
4159 bios_size = BIOS_SIZE;
4160 #ifdef CONFIG_GDBSTUB
4162 gdbstub_port = DEFAULT_GDBSTUB_PORT;
4166 kernel_filename = NULL;
4167 kernel_cmdline = "";
4173 cyls = heads = secs = 0;
4174 translation = BIOS_ATA_TRANSLATION_AUTO;
4175 pstrcpy(monitor_device, sizeof(monitor_device), "vc");
4177 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
4178 for(i = 1; i < MAX_SERIAL_PORTS; i++)
4179 serial_devices[i][0] = '\0';
4180 serial_device_index = 0;
4182 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
4183 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
4184 parallel_devices[i][0] = '\0';
4185 parallel_device_index = 0;
4187 usb_devices_index = 0;
4192 /* default mac address of the first network interface */
4200 hd_filename[0] = argv[optind++];
4202 const QEMUOption *popt;
4205 popt = qemu_options;
4208 fprintf(stderr, "%s: invalid option -- '%s'\n",
4212 if (!strcmp(popt->name, r + 1))
4216 if (popt->flags & HAS_ARG) {
4217 if (optind >= argc) {
4218 fprintf(stderr, "%s: option '%s' requires an argument\n",
4222 optarg = argv[optind++];
4227 switch(popt->index) {
4229 machine = find_machine(optarg);
4232 printf("Supported machines are:\n");
4233 for(m = first_machine; m != NULL; m = m->next) {
4234 printf("%-10s %s%s\n",
4236 m == first_machine ? " (default)" : "");
4241 case QEMU_OPTION_initrd:
4242 initrd_filename = optarg;
4244 case QEMU_OPTION_hda:
4245 case QEMU_OPTION_hdb:
4246 case QEMU_OPTION_hdc:
4247 case QEMU_OPTION_hdd:
4250 hd_index = popt->index - QEMU_OPTION_hda;
4251 hd_filename[hd_index] = optarg;
4252 if (hd_index == cdrom_index)
4256 case QEMU_OPTION_snapshot:
4259 case QEMU_OPTION_hdachs:
4263 cyls = strtol(p, (char **)&p, 0);
4264 if (cyls < 1 || cyls > 16383)
4269 heads = strtol(p, (char **)&p, 0);
4270 if (heads < 1 || heads > 16)
4275 secs = strtol(p, (char **)&p, 0);
4276 if (secs < 1 || secs > 63)
4280 if (!strcmp(p, "none"))
4281 translation = BIOS_ATA_TRANSLATION_NONE;
4282 else if (!strcmp(p, "lba"))
4283 translation = BIOS_ATA_TRANSLATION_LBA;
4284 else if (!strcmp(p, "auto"))
4285 translation = BIOS_ATA_TRANSLATION_AUTO;
4288 } else if (*p != '\0') {
4290 fprintf(stderr, "qemu: invalid physical CHS format\n");
4295 case QEMU_OPTION_nographic:
4296 pstrcpy(monitor_device, sizeof(monitor_device), "stdio");
4297 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "stdio");
4300 case QEMU_OPTION_kernel:
4301 kernel_filename = optarg;
4303 case QEMU_OPTION_append:
4304 kernel_cmdline = optarg;
4306 case QEMU_OPTION_cdrom:
4307 if (cdrom_index >= 0) {
4308 hd_filename[cdrom_index] = optarg;
4311 case QEMU_OPTION_boot:
4312 boot_device = optarg[0];
4313 if (boot_device != 'a' &&
4316 boot_device != 'n' &&
4318 boot_device != 'c' && boot_device != 'd') {
4319 fprintf(stderr, "qemu: invalid boot device '%c'\n", boot_device);
4323 case QEMU_OPTION_fda:
4324 fd_filename[0] = optarg;
4326 case QEMU_OPTION_fdb:
4327 fd_filename[1] = optarg;
4329 case QEMU_OPTION_no_code_copy:
4330 code_copy_enabled = 0;
4332 case QEMU_OPTION_net:
4333 if (nb_net_clients >= MAX_NET_CLIENTS) {
4334 fprintf(stderr, "qemu: too many network clients\n");
4337 pstrcpy(net_clients[nb_net_clients],
4338 sizeof(net_clients[0]),
4343 case QEMU_OPTION_tftp:
4344 tftp_prefix = optarg;
4347 case QEMU_OPTION_smb:
4348 net_slirp_smb(optarg);
4351 case QEMU_OPTION_redir:
4352 net_slirp_redir(optarg);
4356 case QEMU_OPTION_enable_audio:
4363 case QEMU_OPTION_audio_help:
4367 case QEMU_OPTION_soundhw:
4368 select_soundhw (optarg);
4375 ram_size = atoi(optarg) * 1024 * 1024;
4378 if (ram_size > PHYS_RAM_MAX_SIZE) {
4379 fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
4380 PHYS_RAM_MAX_SIZE / (1024 * 1024));
4389 mask = cpu_str_to_log_mask(optarg);
4391 printf("Log items (comma separated):\n");
4392 for(item = cpu_log_items; item->mask != 0; item++) {
4393 printf("%-10s %s\n", item->name, item->help);
4400 #ifdef CONFIG_GDBSTUB
4405 gdbstub_port = atoi(optarg);
4412 start_emulation = 0;
4415 keyboard_layout = optarg;
4417 case QEMU_OPTION_localtime:
4420 case QEMU_OPTION_cirrusvga:
4421 cirrus_vga_enabled = 1;
4423 case QEMU_OPTION_std_vga:
4424 cirrus_vga_enabled = 0;
4431 w = strtol(p, (char **)&p, 10);
4434 fprintf(stderr, "qemu: invalid resolution or depth\n");
4440 h = strtol(p, (char **)&p, 10);
4445 depth = strtol(p, (char **)&p, 10);
4446 if (depth != 8 && depth != 15 && depth != 16 &&
4447 depth != 24 && depth != 32)
4449 } else if (*p == '\0') {
4450 depth = graphic_depth;
4457 graphic_depth = depth;
4460 case QEMU_OPTION_monitor:
4461 pstrcpy(monitor_device, sizeof(monitor_device), optarg);
4463 case QEMU_OPTION_serial:
4464 if (serial_device_index >= MAX_SERIAL_PORTS) {
4465 fprintf(stderr, "qemu: too many serial ports\n");
4468 pstrcpy(serial_devices[serial_device_index],
4469 sizeof(serial_devices[0]), optarg);
4470 serial_device_index++;
4472 case QEMU_OPTION_parallel:
4473 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
4474 fprintf(stderr, "qemu: too many parallel ports\n");
4477 pstrcpy(parallel_devices[parallel_device_index],
4478 sizeof(parallel_devices[0]), optarg);
4479 parallel_device_index++;
4481 case QEMU_OPTION_loadvm:
4484 case QEMU_OPTION_full_screen:
4487 case QEMU_OPTION_pidfile:
4488 create_pidfile(optarg);
4491 case QEMU_OPTION_win2k_hack:
4492 win2k_install_hack = 1;
4496 case QEMU_OPTION_no_kqemu:
4500 case QEMU_OPTION_usb:
4503 case QEMU_OPTION_usbdevice:
4505 if (usb_devices_index >= MAX_VM_USB_PORTS) {
4506 fprintf(stderr, "Too many USB devices\n");
4509 pstrcpy(usb_devices[usb_devices_index],
4510 sizeof(usb_devices[usb_devices_index]),
4512 usb_devices_index++;
4518 linux_boot = (kernel_filename != NULL);
4521 hd_filename[0] == '\0' &&
4522 (cdrom_index >= 0 && hd_filename[cdrom_index] == '\0') &&
4523 fd_filename[0] == '\0')
4526 /* boot to cd by default if no hard disk */
4527 if (hd_filename[0] == '\0' && boot_device == 'c') {
4528 if (fd_filename[0] != '\0')
4534 #if !defined(CONFIG_SOFTMMU)
4535 /* must avoid mmap() usage of glibc by setting a buffer "by hand" */
4537 static uint8_t stdout_buf[4096];
4538 setvbuf(stdout, stdout_buf, _IOLBF, sizeof(stdout_buf));
4541 setvbuf(stdout, NULL, _IOLBF, 0);
4544 /* init network clients */
4545 if (nb_net_clients == 0) {
4546 /* if no clients, we use a default config */
4547 pstrcpy(net_clients[0], sizeof(net_clients[0]),
4549 pstrcpy(net_clients[1], sizeof(net_clients[0]),
4554 for(i = 0;i < nb_net_clients; i++) {
4555 if (net_client_init(net_clients[i]) < 0)
4559 /* init the memory */
4560 phys_ram_size = ram_size + vga_ram_size + bios_size;
4562 #ifdef CONFIG_SOFTMMU
4563 phys_ram_base = qemu_vmalloc(phys_ram_size);
4564 if (!phys_ram_base) {
4565 fprintf(stderr, "Could not allocate physical memory\n");
4569 /* as we must map the same page at several addresses, we must use
4574 tmpdir = getenv("QEMU_TMPDIR");
4577 snprintf(phys_ram_file, sizeof(phys_ram_file), "%s/vlXXXXXX", tmpdir);
4578 if (mkstemp(phys_ram_file) < 0) {
4579 fprintf(stderr, "Could not create temporary memory file '%s'\n",
4583 phys_ram_fd = open(phys_ram_file, O_CREAT | O_TRUNC | O_RDWR, 0600);
4584 if (phys_ram_fd < 0) {
4585 fprintf(stderr, "Could not open temporary memory file '%s'\n",
4589 ftruncate(phys_ram_fd, phys_ram_size);
4590 unlink(phys_ram_file);
4591 phys_ram_base = mmap(get_mmap_addr(phys_ram_size),
4593 PROT_WRITE | PROT_READ, MAP_SHARED | MAP_FIXED,
4595 if (phys_ram_base == MAP_FAILED) {
4596 fprintf(stderr, "Could not map physical memory\n");
4602 /* we always create the cdrom drive, even if no disk is there */
4604 if (cdrom_index >= 0) {
4605 bs_table[cdrom_index] = bdrv_new("cdrom");
4606 bdrv_set_type_hint(bs_table[cdrom_index], BDRV_TYPE_CDROM);
4609 /* open the virtual block devices */
4610 for(i = 0; i < MAX_DISKS; i++) {
4611 if (hd_filename[i]) {
4614 snprintf(buf, sizeof(buf), "hd%c", i + 'a');
4615 bs_table[i] = bdrv_new(buf);
4617 if (bdrv_open(bs_table[i], hd_filename[i], snapshot) < 0) {
4618 fprintf(stderr, "qemu: could not open hard disk image '%s'\n",
4622 if (i == 0 && cyls != 0) {
4623 bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
4624 bdrv_set_translation_hint(bs_table[i], translation);
4629 /* we always create at least one floppy disk */
4630 fd_table[0] = bdrv_new("fda");
4631 bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
4633 for(i = 0; i < MAX_FD; i++) {
4634 if (fd_filename[i]) {
4637 snprintf(buf, sizeof(buf), "fd%c", i + 'a');
4638 fd_table[i] = bdrv_new(buf);
4639 bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
4641 if (fd_filename[i] != '\0') {
4642 if (bdrv_open(fd_table[i], fd_filename[i], snapshot) < 0) {
4643 fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
4651 /* init USB devices */
4653 vm_usb_hub = usb_hub_init(vm_usb_ports, MAX_VM_USB_PORTS);
4654 for(i = 0; i < usb_devices_index; i++) {
4655 if (usb_device_add(usb_devices[i]) < 0) {
4656 fprintf(stderr, "Warning: could not add USB device %s\n",
4662 /* init CPU state */
4665 cpu_single_env = env;
4667 register_savevm("timer", 0, 1, timer_save, timer_load, env);
4668 register_savevm("cpu", 0, 3, cpu_save, cpu_load, env);
4669 register_savevm("ram", 0, 1, ram_save, ram_load, NULL);
4670 qemu_register_reset(main_cpu_reset, global_env);
4673 cpu_calibrate_ticks();
4677 dumb_display_init(ds);
4679 #if defined(CONFIG_SDL)
4680 sdl_display_init(ds, full_screen);
4681 #elif defined(CONFIG_COCOA)
4682 cocoa_display_init(ds, full_screen);
4684 dumb_display_init(ds);
4688 vga_console = graphic_console_init(ds);
4690 monitor_hd = qemu_chr_open(monitor_device);
4692 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
4695 monitor_init(monitor_hd, !nographic);
4697 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
4698 if (serial_devices[i][0] != '\0') {
4699 serial_hds[i] = qemu_chr_open(serial_devices[i]);
4700 if (!serial_hds[i]) {
4701 fprintf(stderr, "qemu: could not open serial device '%s'\n",
4705 if (!strcmp(serial_devices[i], "vc"))
4706 qemu_chr_printf(serial_hds[i], "serial%d console\n", i);
4710 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
4711 if (parallel_devices[i][0] != '\0') {
4712 parallel_hds[i] = qemu_chr_open(parallel_devices[i]);
4713 if (!parallel_hds[i]) {
4714 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
4715 parallel_devices[i]);
4718 if (!strcmp(parallel_devices[i], "vc"))
4719 qemu_chr_printf(parallel_hds[i], "parallel%d console\n", i);
4723 /* setup cpu signal handlers for MMU / self modifying code handling */
4724 #if !defined(CONFIG_SOFTMMU)
4726 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
4729 signal_stack = memalign(16, SIGNAL_STACK_SIZE);
4730 stk.ss_sp = signal_stack;
4731 stk.ss_size = SIGNAL_STACK_SIZE;
4734 if (sigaltstack(&stk, NULL) < 0) {
4735 perror("sigaltstack");
4741 struct sigaction act;
4743 sigfillset(&act.sa_mask);
4744 act.sa_flags = SA_SIGINFO;
4745 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
4746 act.sa_flags |= SA_ONSTACK;
4748 act.sa_sigaction = host_segv_handler;
4749 sigaction(SIGSEGV, &act, NULL);
4750 sigaction(SIGBUS, &act, NULL);
4751 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
4752 sigaction(SIGFPE, &act, NULL);
4759 struct sigaction act;
4760 sigfillset(&act.sa_mask);
4762 act.sa_handler = SIG_IGN;
4763 sigaction(SIGPIPE, &act, NULL);
4768 machine->init(ram_size, vga_ram_size, boot_device,
4769 ds, fd_filename, snapshot,
4770 kernel_filename, kernel_cmdline, initrd_filename);
4772 gui_timer = qemu_new_timer(rt_clock, gui_update, NULL);
4773 qemu_mod_timer(gui_timer, qemu_get_clock(rt_clock));
4775 #ifdef CONFIG_GDBSTUB
4777 if (gdbserver_start(gdbstub_port) < 0) {
4778 fprintf(stderr, "Could not open gdbserver socket on port %d\n",
4782 printf("Waiting gdb connection on port %d\n", gdbstub_port);
4787 qemu_loadvm(loadvm);
4790 /* XXX: simplify init */
4792 if (start_emulation) {